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?
Answer: There are at least two ways to loop over all the elements in a Perl hash. You can use either (a) a Perl foreach loop, or (b) a Perl while loop with the each function. I find the Perl foreach syntax easier to remember, but the solution with the while loop and the each function is preferred for larger hashes.
Dereference a HASH First we print it out directly so you can see it is really a reference to a HASH. Then we print out the content using the standard Data::Dumper module. Then we de-reference it by putting a % sign in-front of it %$hr and copy the content to another variable called %h.
@values = @{ $hash{"a key"} }; To append a new value to the array of values associated with a particular key, use push : push @{ $hash{"a key"} }, $value; The classic application of these data structures is inverting a hash that has many keys with the same associated value.
foreach my $key (keys %$ad_grp_ref) { ... }
Perl::Critic
and daxim recommend the style
foreach my $key (keys %{ $ad_grp_ref }) { ... }
out 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 }
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With