On 4/18/07, yitzle <[EMAIL PROTECTED]> wrote:

I got an array of hashes so I am using a foreach (@arr) loop to access
the hashes.
How do I go about looping through the hash's keys/values? I was
thinking of another foreach, but then the $_ gets a bit screwed up...

Do I need to do this ?
foreach(@arr) {
  %hash = %{$_};
  foreach (keys %hash) {
    print "$_ => $hash{$_}\n";
  }
}

This is a good time to avoid the foreach loop's default control
variable. Although $_ is handy for small loops, larger (and nested)
ones should generally name another control variable. By giving a name
to the control variable, you should be able to access the hash without
copying the data to another %hash variable. Perl even has special
syntax you can use if the reference is in a scalar variable. It can
even be a 'my' variable:

 my @arr = (  # just some sample hash references
   { qw/ fred flintstone barney rubble wilma flintstone betty rubble / },
   { qw/ 4 ! 2 potato 3 potato 1 potato / },
   { qw/ 4 gotten 2 cool /, '2 ', 'B' },
 );

 foreach my $href (@arr) {
   foreach (sort keys %$href) {
     print "$_ => $href->{$_}\n";
   }
   print "\n";
 }

Hope this helps!

--Tom Phoenix
Stonehenge Perl Training

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to