How to create an array of hashes and loop through them in Perl?

I am trying to create an array of hashes, but I am having problems with a loop in the array. I tried this code but it does not work:

for ($i = 0; $i<@pattern; $i++){ while(($k, $v)= each $pattern[$i]){ debug(" $k: $v"); } } 
+4
source share
3 answers

First, why don't you use ing strict and warnings ? The following lines should be at the top of every Perl program you create right after #!/usr/bin/perl . Always.

 use strict; use warnings; 

And I know that you are not because I am sure that you will get good error messages from strict and warnings , as well as from many other places in your code, judging by your use of the variable.

Secondly, why you are not doing this:

 for my $i (@pattern) { .. } 

This loop goes through each element in @pattern , assigning them $i one at a time. Then in your loop, when you want to get a specific item, just use $i . Changes to $i will be reflected in @pattern , and when the loop goes out, $i will go out of scope, essentially clearing after itself.

Third, for the love of Larry Wall, please declare your my variables to localize them. It really is not that difficult, and it makes you a better person, I promise.

Fourth, and last, your array stores hash references, not hashes. If they store hashes, your code will be wrong because the hashes start with % , not $ . Be that as it may, links (of any kind) are scalar values ​​and thus begin with $ . Therefore, we need to dereference them to get hashes:

 for my $i (@pattern) { while(my($k, $v) = each %{$i}) { debug(" $k: $v"); } } 

Or, in your opinion:

 for (my $i = 0; $i<@pattern; $i++) { # added a my() for good measure while(my($k, $v) = each %{$pattern[$i]}) { debug(" $k: $v"); } } 
+24
source

Try this instead:

 for my $hashref (@pattern) { for my $key (keys %$hashref) { debug "$key: $hashref->{$key}"; } } 

The biggest problem with what you tried was each $pattern[$i] . The each function expects the hash to work, but $pattern[$i] returns hashref (that is, a hash reference). You can fix your code by dereferencing $pattern[$i] as a hash:

 while(my($k, $v) = each %{$pattern[$i]}) { 

Also, beware of every function; it can leave the hash iterator in an incomplete state .

+6
source

See the perl data structures cookbook documentation: perldoc perldsc

+4
source

All Articles