Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl: how to understand @$ref[0]?

Tags:

reference

perl

perl question about ref.

$ref = [11, 22, 33, 44];
print "$$ref[0]" . "\n";
print "@$ref[0]" . "\n";

when i run perl -d.

DB<1> p @$ref
11223344
DB<2> p $ref
ARRAY(0x9dbf480)
DB<3> p \$$ref[0]
SCALAR(0x9dbf470)
DB<4> p \@$ref[0]
SCALAR(0x9dbf470) 

$$ref[0] stands first scalar of ARRAY(0x9dbf480).

what does mean @$ref[0]? i cannot understand.

like image 259
Nihao Web Avatar asked Jun 17 '12 02:06

Nihao Web


2 Answers

$ref = [11, 22, 33, 44]; is a reference to an anonymous array.

$$ref[0] or ${$ref}[0] or $ref->[0] is dereferencing the array and retrieving the first element.

@$ref[0] or @{$ref}[0] is dereferencing the array and getting an array slice that contains only the first element.

like image 52
Matt Coughlin Avatar answered Oct 22 '22 17:10

Matt Coughlin


First, @$ref[0] is different from \@$ref[0]. You have the former in your debug session, and the latter in your script.

Anyway, @$ref[0] means the same thing as @{$ref}[0]. If you had an array named @ref, @ref[0] would be the equivalent. It's using slice notation to get the first element of the array.

The difference between @array[$x] and $array[$x] is that in the first one you can specify more than one index and get back a collection of elements from the array, instead of just one. But if you only put one index between the brackets, you get the same result.

like image 41
Mark Reed Avatar answered Oct 22 '22 15:10

Mark Reed