简体   繁体   中英

Perl: Dereferencing Array

Why does the following code not work in getting into an anonymous array?

   my @d = [3,5,7];
   print $(@{$d[0]}[0]);  

   # but print $d[0][0] works.

Script 1 (original)

Because it is invalid Perl code?

#!/usr/bin/env perl
use strict;
use warnings;

my @d = [3,5,7];
print $(@{$d[0]}[0]); 

When compiled ( perl -c ) with Perl 5.14.1, it yields:

Array found where operator expected at xx.pl line 6, at end of line
    (Missing operator before ?)
syntax error at xx.pl line 6, near "])"
xx.pl had compilation errors.

Frankly, I'm not sure why you expected it to work. I can't make head or tail of what you were trying to do.

The alternative:

print $d[0][0];

works fine because d is an array containing a single array ref. Thus $d[0] is the array (3, 5, 7) (note parentheses instead of square brackets), so $d[0][0] is the zeroth element of the array, which is the 3.

Script 2

This modification of your code prints 3 and 6:

#!/usr/bin/env perl
use strict;
use warnings;

my @d = ( [3,5,7], [4,6,8] );
print $d[0][0], "\n";
print $d[1][1], "\n";

Question

So the $ in $d[0] indicates that [3,5,7] is dereferenced to the array (3,5,7) , or what does the $ do here? I thought the $ was to indicate that a scalar was getting printed out?

Roughly speaking, a reference is a scalar, but a special sort of scalar.

If you do print "$d[0]\\n"; you get output something like ARRAY(0x100802eb8) , indicating it is a reference to an array. The second subscript could also be written as $d[0]->[0] to indicate that there's another level of dereferencing going on. You could also write print @{$d[0]}, "\\n"; to print out all the elements in the array.

Script 3

#!/usr/bin/env perl
use strict;
use warnings;

$, = ", ";

my @d = ( [3,5,7], [4,6,8] );
#print $(@{$d[0]}[0]); 
print @d, "\n";
print $d[0], "\n";
print @{$d[0]}, "\n";
print @{$d[1]}, "\n";
print $d[0][0], "\n";
print $d[1][1], "\n";
print $d[0]->[0], "\n";
print $d[1]->[1], "\n";

Output

ARRAY(0x100802eb8), ARRAY(0x100826d18), 
ARRAY(0x100802eb8), 
3, 5, 7, 
4, 6, 8, 
3, 
6, 
3, 
6, 

I think you are trying for this:

${$d[0]}[0]

Though of course there's always the syntactic sugar way, too:

$d[0]->[0]

The square bracket constructor creates an anonymous array, but you are storing it in another array. This means that you are storing the three element array inside the first element of a one element array. This is why $d[0][0] will return the value 3 . To do a single level array use the list constructor:

my @d = (3,5,7);
print $d[0];

If you really mean to create the array inside the outer array then you should dereference the single (scalar) value as

print ${$d[0]}[0].

For more read perldoc perlreftut .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM