I have this code
foreach my $key (keys %ad_grp) {
# Do something
}
which works.
How would the same look like, if I don't have %ad_grp
, but a reference, $ad_grp_ref
, to the hash?
I have this code
foreach my $key (keys %ad_grp) {
# Do something
}
which works.
How would the same look like, if I don't have %ad_grp
, but a reference, $ad_grp_ref
, to the hash?
So, with Perl 5.20, the new answer is:
(which has the advantage of transparently working with more complicated expressions:
etc.)
See perlref for the full documentation.
Note: in Perl version 5.20 and 5.22, this syntax is considered experimental, so you need
at the top of any file that uses it. Perl 5.24 and later don't require any pragmas for this feature.
Perl::Critic
and daxim recommend the styleout of concerns for readability and maintenance (so that you don't need to think hard about what to change when you need to use
%{ $ad_grp_obj[3]->get_ref() }
instead of%{ $ad_grp_ref }
)As others have stated, you have to dereference the reference. The
keys
function requires that its argument starts with a %:My preference:
According to Conway:
Guess who you should listen to...
You might want to read through the Perl Reference Documentation.
If you find yourself doing a lot of stuff with references to hashes and hashes of lists and lists of hashes, you might want to start thinking about using Object Oriented Perl. There's a lot of nice little tutorials in the Perl documentation.
In Perl 5.14 (it works in now in Perl 5.13), we'll be able to just use keys on the hash reference