You need to pass each of the arrays as a reference, otherwise your @x
in the sub will gobble up the ENTIRE array of arguments, leaving @y
an empty arraay and $z
an undef value.
This happens because the comma operator - in a list context - will turn a @x, @y, $z
into a single array consisting of all the elements of @x
followed by all elements of @y
and then a value of $z
; your @x
in the sub will gobble up the ENTIRE combined array of arguments, leaving @y
an empty array and $z
an undef value.
Another possible source of confusion is the fact that you named both variables @x
, despite the fact that they are completely independent of each other due to scoping rules. Good practice would be to name them something distinct to avoid having to guess which one you meant to use, e.g. call the subroutine's first array @x2
.
Please note that you can pass the array as a reference in one of two ways - the reference to the original array (real pass-by-reference approach) as well as reference to a COPY of the array - which will behave like you wanted your origainal code to behave and pass by value.
use strict; use warnings;
my @x = qw(AAAA BBBB CCCC DDDD EEEE);
my @y = qw(1111 2222 3333 4444 5555);
my $z = "hello";
Hello(\@x,\@y,$z);
# If you wish to pass a reference of a COPY of the array,
# so that you can modify it inside the subroutine without modifying the original,
# instead call Hello([@x], [@y], $z);
exit(0);
sub Hello {
my ($x2,$y2,$z2) = @_;
# Now, you de-reference array reference $x2 via @$x2 or $x2->[$i]
# where previously you used @x2 or $x2[$i]
print "$_\n" for @$x2;
print "$_\n";
print "$_\n" for @$y2;
print "$_\n";
print "$z2\n";
}