I am trying to access elements of arrays by reference, passing references into a sub. Here is my code snippet:
my @arr1 = (1,2);
my @arr2 = (3,4);
my @arr3;
push @arr3, \@arr1;
push @arr3, \@arr2;
for my $i (@arr3) {
print "$i\n";
}
print "Entered Sub func()\n";
for my $i (@arr3) {
func($i);
}
sub func{
my $par = shift;
print $par."\n";
}
print "------------------------\n";
for my $elem(@$par) {
print $elem."\n";
}
And here is the ouput:
C:\Users\ag194y>perl arrs.pl
ARRAY(0x357b28)
ARRAY(0x3575e8)
Entered Sub func()
ARRAY(0x357b28)
ARRAY(0x3575e8)
------------------------
C:\Users\ag194y>
I was expecting to access the elements of @arr1 and a@rr2 with the for loop in the sub, but it looks like array refs are empty. What am I doing wrong? Many thanks.
I think the problem is, loop being outside of func
. You are calling func
twice, and only after that you are looping through $par
, which is undefined at the time.
You might be looking for something like:
sub func{
my $par = shift;
print $par."\n";
print "------------------------\n";
for my $elem (@$par){
print $elem."\n";
}
}