Sequential statements and parentheses

I'm just trying to learn a little Perl and stumbled upon this:

foreach $element (@{$records}) { do something; } 

For my newbies, it says: "for each element of the array named @ {$ records}, do something" but since this seems like an unlikely name for the array (with " @{$ " in general), I think it's not simply?

I also met the " %$ " used together. I know that % means hash, and $ means scalar, but does not know what they mean together.

Can anyone shed light on them?

+6
source share
2 answers

In Perl, you can have a link (pointer) to a data structure:

 # an array my @array; # a reference to an array my $ref = \@array; 

When you have a link, to be able to use an array, you need to dereference it

 @{ $ref } 

If you need to access an element, as in

 $array[0] 

you can do the same with reference

 ${$ref}[0] 

braces {} are optional and you can also use

 $$ref[0] @$ref 

but I personally find them less readable.

The same applies to all other types (like %$ for a hash link).

See man perlref and man perlreftut for a tutorial for more details.

Edit

The arrow operator -> can also be used to dereference an array or hash

 $array_ref->[0] 

or

 $hash_ref->{key} 

See man perlop for more details.

+10
source

If you have a reference to an array or a hash, you should use a scalar to store the link:

 my $href = \%hash; my $aref = \@array; 

If you want to cancel links to these links, you must use the character corresponding to the link type:

 for my $element (@$aref) { } for my $key (keys %$href) { } 
+3
source

Source: https://habr.com/ru/post/924852/


All Articles