Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use foreach with a hash reference?

Tags:

hash

perl

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?

like image 512
Sandra Schlichting Avatar asked Mar 09 '11 17:03

Sandra Schlichting


People also ask

How to loop through hash Perl?

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.

How do I dereference a hash in Perl?

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.

How do I declare an array of hash in Perl?

@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.


1 Answers

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 })

like image 166
mob Avatar answered Sep 24 '22 04:09

mob