Perl syntax regarding links

Consider x - this is an array reference.

I know that [] gives a reference to an anonymous array, and {} gives an anonymous hash reference. What does @{$x} mean?

+4
source share
4 answers

This means dereferencing the ref array.

You will see the contents of the reference array.

Please note that you can use simple

 @$x 

in your case.

The { } characters are necessary if there are several levels in your data structure, as in this example:

 @{ $foo->{first_level}->{second_level} } 

or

 @{ $foo->[$first_level]->[$second_level] } 

This also works with other sigils :

 %{ } # HASH $ # SCALAR 

See perldoc perlreftut

+8
source

This is dereferencing. @{ $ref } refers to references as @array refers to arrays, that is, you should use @{ $ref } wherever you use @array .

 >perl -E"@array = qw( abc ); say $_ for @array;" a b c >perl -E"$ref = [qw( abc )]; say $_ for @{ $ref };" a b c 

Amounts may be omitted for certainty.

 >perl -E"$ref = [qw( abc )]; say $_ for @$ref;" a b c 
+8
source

if $x is an array reference, as in

 @a = (1,2,3); $x = \@a 

then with @$x or @{$x} , you will return @a .

+4
source

Depends on the context and what follows. In a scalar context:

 $y = @{$x}; 

it will return the number of elements in the array to which $x is a reference.

In the context of the list:

 @y = @{$x}; 

it will return the elements of the array.

If followed by [LIST] :

 @{$x}[1,42] 

it creates a slice of the array, a list of the specified elements in the array to which $x is a reference.

If you follow {LIST} :

 @{$x}{ 'foo', 'bar' } 

it creates a hash slice, a list of values ​​for the specified keys in the hash, to which $x is a link.

Link to links

Note that the {} around $x not related to the {} used to build the anonymous hash, they are code block delimiters. If what is in them is a simple scalar variable, they can be skipped; if they are not omitted, they may contain an arbitrary expression or even several statements that return a link at the end.

+1
source

All Articles