I want to pass an array of function [...] with another output. Why did this happen?
You cannot pass an array to a function . Subs can only accept a list of scalars as arguments.
test_func("test_func", 10, @test1);
coincides with
test_func("test_func", 10, $test1[0], $test1[1], $test1[2], $test1[3], $test1[4]);
You create a new array in test_func
when you execute
my ($name, $num, @array) = @_;
shift
returns the first @_
element, which is necessarily a scalar. @_
is an array, and array elements are scalars. Equivalent to be
my $name = shift(@_); my $num = shift(@_); my @array = splice(@_);
To pass an array to sub, you can usually pass a reference to it.
test_func("test_func", 10, \@test1); my ($name, $num, $array) = @_; my $name = shift; my $num = shift; my $array = shift; say "@$array";
But the argument passed changes in the function. Is this called by value?
Perl never goes by value. It always follows the link. If you change any @_
element, it will change the corresponding argument in the caller.
$ perl -E'sub f { $_[0] = "def"; } my $x = "abc"; f($x); say $x;' def
But it's not a problem. You do not change any @_
elements. What you are doing is changing the only array referenced by both $test[0]
and $array[0]
.
This is what you do:
my $ref1 = [ 'a', 1 ];
This is short for
my @anon = ( 'a', 1 ); my $ref1 = \@anon;
Storable dclone
can be used to create a deep copy of an array.
my $ref1 = [ 'a', 1 ]; my $ref2 = dclone($ref1);