Reputation: 47
Example:
for my $key ( keys %DNS_CSV_FILES){
for my $file (@$DNS_CSV_FILES{$key}){
print $file;
}
}
gives the error:
Global symbol "$DNS_CSV_FILES" requires explicit package name (did you forget to declare "my $DNS_CSV_FILES"?) at dns.pl line 41.
Execution of dns.pl aborted due to compilation errors.
But this code:
for my $key ( keys %DNS_CSV_FILES){
for my $file (@{$DNS_CSV_FILES{$key}}){
print $file;
}
}
gives the desired output:
file1.txtfile2.txt
Upvotes: 1
Views: 125
Reputation: 132775
In short, Perl's dereference syntax puts braces around the reference. However, you can leave off the braces if the reference is simple scalar, like $value
. For anything else, including a hash key lookup, you keep the braces.
That's the old-style "circumfix" notation. Perl v5.24 stabilized the postfix dereference syntax.
Upvotes: 1
Reputation: 385590
@$x{ $key }
is short for @{ $x }{ $key }
, not @{ $x{ $key } }
.
See Perl Dereferencing Syntax. Footnote [1] in particular. The curlies can only be omitted around a simple scalar variable.
There is no difference between @{ $x }
and @$x
. But that's not what the two snippets are using.
The first is using @$x{ $key }
, which is short for @{ $x }{ $key }
.
There is a difference between @{ $x }{ $key }
and @{ $x{ $key } }
.
@foo{ $key }
is a slice of a named array, so @{ ... }{ $key }
is a slice of a referenced array. @{ $DNS_CSV_FILES }{ $key }
is therefore a slice of the array referenced by scalar $DNS_CSV_FILES
.
@foo
is a array provided by name, so @{ ... }
is a referenced array. @{ $DNS_CSV_FILES{ $key } }
is therefore an array referenced by hash element $DNS_CSV_FILES{ $key }
.
Upvotes: 2
Reputation: 67900
This
@$DNS_CSV_FILES{$key}
Will from the left side see an array sigil @
followed by a scalar $
. This can only be the dereferencing of an array ref. Otherwise the @
is a syntax error. Despite you putting the hash notation at the end. It is a race condition, of sorts. So it will assume that what follows is a scalar, and not a hash value.
When you clarify by adding extra brackets, it becomes clear what is intended
@{ $DNS_CSV_FILES{$key} }
Whatever is inside @{ }
must be an array ref, and $....{key}
must be a hash value.
Upvotes: 0