consecutive operators and brackets
Asked Answered
G

2

6

I'm just trying to learn a bit of Perl and have come across this:

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

To my newbie eyes, this reads: "for each element in an array named @{$records}, do something" but, since that seems an unlikely name for an array (with "@{$" altogether), I imagine it isn't that simple?

I've also come across "%$" used together. I know % signifies a hash and $ signifies a scalar but don't know what they mean together.

Can anyone shed any light on these?

Goerke answered 7/9, 2012 at 13:20 Comment(0)
J
10

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

# an array
my @array;

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

When you have a reference to be able to use the array you need to dereference it

@{ $ref }

If you need to access an element as in

$array[0]

you can do the same with a reference

${$ref}[0]

The curly brackets {} are optional and you can also use

$$ref[0]
@$ref

but I personally find them less readable.

The same applies to every other type (as %$ for a hash reference).

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

Edit

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

$array_ref->[0]

or

$hash_ref->{key}

See man perlop for details

Japanese answered 7/9, 2012 at 13:24 Comment(3)
I prefer to access a single element in an array reference with $array->[0]Vernice
@LeonardoHerrera Thanks (I completely forgot but it is worth to mention it as it is widely used especially with hashes). I updated the answer.Japanese
3 or is it 4 ways to get an array element when given an array reference. I wonder how many there are in Perl 6? 3 ways gets a little confusing.Fetching
C
3

If you have a reference to an array or a hash, you would use a scalar to hold the reference:

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

When you want to de-reference these references, you would use the symbol appropriate for the reference type:

for my $element (@$aref) {
}

for my $key (keys %$href) {
}
Cowl answered 7/9, 2012 at 13:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.