'What is the difference between @{$value} and @$value in perl?
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
Solution 1:[1]
@$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 }.
Solution 2:[2]
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.
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ikegami |
| Solution 2 | brian d foy |
| Solution 3 | TLP |
