In the following Perl code, I would expect to be referencing an array reference inside an array
#!/usr/bin/perl
use strict;
use warnings;
my @a=([1,2],[3,4]);
my @b = @$a[0];
print $b[0];
However it doesn't seem to work. I would expect it to output 1.
@a
is an array of references
@b
is $a[1]
dereferenced (I think)
So what's the problem?
Perl anonymous references These types of references are called anonymous references. The rules of creating anonymous references are as follows: To get an array reference, use square brackets [] instead of parentheses. To get a hash reference, use curly brackets {} instead of parentheses.
A simple way to check if an array is null or defined is to examine it in a scalar context to obtain the number of elements in the array. If the array is empty, it will return 0, which Perl will also evaluate as boolean false.
This stuff is tricky.
@$a[0]
is parsed as (@$a)[0]
, dereferencing the (undefined) scalar $a
You wanted to say @{$a[0]}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With