I am trying to use a reference to an array in various ways that I understand can be done.
Here's one of my trial: -
my $RoR = [[2, 3], [4, 5, 7]];
my @AoA = ([2, 3], [[2, 3], [4, 5, 7]]);
my @AwR = ([2, 3], @{$RoR});
print $AoA[1][1][1], "\n"; # 1
print $AoA[1]->[1][1], "\n"; # 2
#print $RoR[0][1], "\n"; # 3
print $RoR->[0][1], "\n"; # 4
print $AwR[1][1][1], "\n"; # 5
print $AwR[1]->[1][1], "\n"; # 6
As you can see, I have three different arrays.
$RoR-> Is a reference to an anonymous array, which contains two anonymous arrays@AoA-> Is an array containing 2 anonymous array. 2nd anonymous array is same as the array pointed to by the reference$RoR@AwR-> Is almost same as@AoA, but with a difference that, rather than having a new anonymous array, I have added the reference@{$RoR}itself, inside it. So, basically I think, the last two arrays are practically the same.
Now, the problem is, they are not behaving in the same way.
The print statements
1, and2are working fine, and printing out the value5as result.The print statement
3is giving error, which I know why, so no problem in it. The print statement4is printing the value3, as expected.Now, the print statement
5and6are throwing some errors when I try to run the program."Can't use string ("2") as an ARRAY ref while \"strict refs\" in use at D:/_Perl Practice/3perldsc/array_of_array.pl line 15."
Then I tried using: -
print $AwR[1][1]->[1], "\n";
print @{$RoR}[1]->[1];
Where, I replaced $AwR[1] with @{$RoR}, as $AwR[1] contains @{$RoR}. The second one is working fine, while the first one is still throwing error.
So, what exactly is the difference between the 1st two and the last two print statements? I thought they are the same, and hence should give same result for same index access. But it is not. Am I using the reference in some wrong way?
Ok, now above doubt is clear. So, I have posted an answer accumulating the general stuff related to this question. Please take a look at it below. In that, I have a doubt in the 5th and 6th print statement, and to understand it I tried the below test: -
print $AwR[1][1]; # Allowed as `$AwR[1]` is same as `$$RoR`.
print $$RoR[1]; # Allowed as in 3(b)
print $AwR[1]->[1]; # Confused here. It is allowed
print $$RoR->[1]; # But this is not.
The first three statement are printing the same reference value. But the last one is failing. So, its sure that :- $AwR[1] is same as $$RoR. But, why $$RoR->[1] is not working while $AwR[1]->[1] is working? It's throwing me this error: -
Not a SCALAR reference at D:/_Perl Practice/3perldsc/array_of_array.pl line 24.
So, what's the difference in using it in two different way?
perldoc perlreftut, it really helped me learn these things!