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

Marius picture Marius · Aug 24, 2009 · Viewed 11.5k times · Source

I'm trying to create an array of hashes, but I'm having trouble looping through the array. I have tried this code, but it does not work:

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

Answer

Chris Lutz picture Chris Lutz · Aug 24, 2009

First, why aren't you useing 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 you aren't because I'm pretty sure you'd get some nice error messages out of strict and warnings from this, and from many other places in your code as well, judging by your variable use.

Second, why aren't you doing this:

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

That loops through every element in @pattern, assigning them to $i one at a time. Then, in your loop, when you want a particular element, just use $i. Changes to $i will be reflected in @pattern, and when the loop exits, $i will fall out of scope, essentially cleaning up after itself.

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

Fourth, and last, your array stores references to hashes, not hashes. If they stored hashes, your code would be wrong because hashes start with %, not $. As it is, references (of any kind) are scalar values, and thus start with $. So we need to dereference them to get hashes:

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

Or, your way:

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