I am trying to send an array as a parameter in one of my functions in Perl.
e.g
my @array = ("dog", "cat", "mouse", 234, "my uncle Bill");
&sendArray(@array);
sub sendArray {
my @sub_array = shift;
print @sub_array;
}
~~~~~~~ ¦¦ ~~~~~~
This will only print the first element of the array. Any help will be very appreciated.
cheers.
Note that because of this behaviour it is not possible to pass an array as the first argument and a scalar value or second array as a second argument of a function call.
@names = q [perldoc.com]w(aaron nick stevie);
$name = 'jesse';
my_function(@names, $name);
sub my_function {
(@lnames, $lname) = @_;
print [perldoc.com] "\@lnames: ", join [perldoc.com](' ', @lnames), "\n";
print [perldoc.com] "\$lname: $lname\n";
}
will print
@lnames: aaron nick stevie jesse
$lname:
All arguments were flattened into a list and copied to @lnames. To pass multiple arrays you need to pass a reference to the array.
@names = q [perldoc.com]w(aaron nick stevie);
$name = 'jesse';
my_function(\@names, $name);
sub my_function {
($lnames_ref, $lname) = @_;
print [perldoc.com] "\@names: ", join [perldoc.com](' ', @$lnames_ref), "\n";
print [perldoc.com] "\$lname: $lname\n";
}
will output
@lnames: aaron nick stevie
$lname: jesse
Andreas
let's say I have a function returning two arrays
(@first, @second) = &my_subroutine($i);
sub my_subroutine{
my $scalar = shift;
###do something....
return (@array1, @array2);
}
-----------------------------------------------
This will flatten @array1 and @array2 in @first!
Any idea how to get around this?
Thanks
[edited by: jean_dave80 at 5:21 am (utc) on April 29, 2003]
Shawn
Not. The arrays will stick around until there is no longer any reference pointing to them. So if you return a reference to some arrays you can still dereference them in your main script although the actual arrays have gone out of scope.
sub test {
my @a1 = qw(aaron nick);
my @a2 = qw(taylor zac);
return (\@a1, \@a2);
}
#
(my $a1, my $a2) = test();
#
print join(' and ', @$a1), "\n", join(' and ', @$a2);
will print
aaron and nick
taylor and zac
Andreas