ewhitt has asked for the wisdom of the Perl Monks concerning the following question:

I have a hash that looks like this from a Data::Dumper
$VAR1 = 'summary'; $VAR2 = { 'allotments' => 679 }; $VAR3 = 'prefix'; $VAR4 = { '32 ' => 425, '45 ' => 5, '41 ' => 2, '46 ' => 5, '44 ' => 1, '47 ' => 9, '43 ' => 1, '27 ' => 1, '48 ' => 212, '22 ' => 14, '29 ' => 2, '40 ' => 2 };
I am trying to loop through the keys, but everything under "prefix" is unique every execution.
for (@{$hash->{'prefix'}}) { print "$_\n"; }
How can I "wildcard" everything under "prefix" to print the key values?

Replies are listed 'Best First'.
Re: Need help looping through hash
by Fletch (Bishop) on Aug 29, 2008 at 23:46 UTC

    I think you're seeking keys, and its friends values and each. Together this rag-tag bunch of former special ops members travels the country in a custom van helping those in need.

    Wait, no. They let you iterate over hash contents. I think I got them confused with the A Team. Must be the similar mohawks . . .

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

      I am trying this, but with no success. How far off base am I?
      for my $key (keys %$hash) { print "$hash->{'prefix'}->{$key}" }
        No cigar either...
        foreach my $k1 ( keys %{ $hash{'prefix'} } ) { for my $k2 ( keys %{ $hash{$k1} } ) { print("$k2\n"); } }
Re: Need help looping through hash
by toolic (Bishop) on Aug 30, 2008 at 00:24 UTC
      $VAR1 = { 'summary' => { 'allotments' => 679 }, 'prefix' => { '32 ' => 425, '45 ' => 5, '41 ' => 2, '46 ' => 5, '44 ' => 1, '47 ' => 9, '43 ' => 1, '27 ' => 1, '48 ' => 212, '22 ' => 14, '29 ' => 2, '40 ' => 2 } };
      Thanks for the "\" advice for Data::Dumper. That does look a lot better. I will read the URLs that everyone suggested and see what I come up with. Thanks again!
Re: Need help looping through hash
by cosmicperl (Chaplain) on Aug 31, 2008 at 00:43 UTC
    Hi,
      Could you show us the code you are using for the Dump? As this looks like 4 variables rather than a hash. Maybe you need to be dumping as a reference with \%hash?
      As far as looping goes (untested code and it's late):-
    foreach my $key (keys %hash) { print "$key = $hash{$key}\n"; }#foreach foreach my $value (values %hash) { print "value = $value\n"; }#foreach while ( my ($key, $value) = each %hash ) { print "$key = $value\n"; }#while

    Lyle
      Lyle, here is a Dump with \%hash
      $VAR1 = { 'summary' => { 'allotments' => 679 }, 'prefix' => { '32 ' => 425, '45 ' => 5, '41 ' => 2, '46 ' => 5, '44 ' => 1, '47 ' => 9, '43 ' => 1, '27 ' => 1, '48 ' => 212, '22 ' => 14, '29 ' => 2, '40 ' => 2 } };
      What I am trying to do is jump into the HoH to the keys under "prefix" and print their corresponding values. (i.e. that "32" = "425", "45" = 5...etc). Can't this be done in a single loop? Something like
      foreach my $key (keys $%hash->{'prefix'})