Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why dereference is not necessary here?

Tags:

perl

my $arr = [[2,4],[1,3]];
print $$arr[0]->[1];

It prints 1 as expected.

If I remove the dereference:

my $arr = [[2,4],[1,3]];
print $$arr[0][1];

It still works and no warning at all? Why?

like image 764
SwiftMango Avatar asked Jan 21 '26 23:01

SwiftMango


1 Answers

The dereference is always assumed between any {} and []. The following are identical:

print $var[2]{key}[3][5];

and

print $var[2]->{key}->[3]->[5];

From the docs

perlreftut #Arrow Rule

In between two subscripts, the arrow is optional.

Instead of $a[1]->[2], we can write $a[1][2] ; it means the same thing. Instead of $a[0]->[1] = 23 , we can write $a[0][1] = 23 ; it means the same thing.

Now it really looks like two-dimensional arrays!

You can see why the arrows are important. Without them, we would have had to write ${$a[1]}[2] instead of $a[1][2] . For three-dimensional arrays, they let us write $x[2][3][5] instead of the unreadable ${${$x[2]}[3]}[5] .

perlref #Using References, section 3:

The arrow is optional between brackets subscripts

like image 153
Miller Avatar answered Jan 24 '26 18:01

Miller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!