Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Hash with three keys

by Jeri (Scribe)
on Dec 12, 2013 at 21:00 UTC ( [id://1066916]=perlquestion: print w/replies, xml ) Need Help??

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

I have an issue that I need to loop over a hash that has three keys. I have written code to loop over two keys before but for some reason I am struggling with this task. Example of code used to loop over two key hash
foreach my $key1 (sort keys %hash){ foreach my $key2 (sort keys %{$hash{$key1}}){ print "$key1\t$key2\t$hash{$key1}{$key2}\n"; } }
I really think the three key structure is best for this task as I have a very complicated structure.
foreach my $key1 (sort keys %hash){ foreach my $key2 (sort keys %{$hash{$key1}} ){ foreach my $key3 (sort keys %{$hash{$hash{$key1}} } ){ print OFH "$key1\t$key2\t$key3\t$hash{$key1}{$key2}{$key3} +\n"; } } }
Thanks

Replies are listed 'Best First'.
Re: Hash with three keys
by AnomalousMonk (Archbishop) on Dec 12, 2013 at 21:15 UTC
    foreach my $key3 (sort keys  %{$hash{$hash{$key1}} }       ){ ... }

    This may serve you better (untested):
        foreach my $key3 (sort keys %{ $hash{$key1}{$key2} }) { ... }
    Also note that with Perl version 5.14+, keys et al will take a hash reference directly: see  keys EXPR

      thanks everyone. got it working :)
Re: Hash with three keys
by hdb (Monsignor) on Dec 12, 2013 at 21:46 UTC

    Recursion is another solution to this, especially if you do not know upfront how deep your hashes are nested or if the depth is not the same everywhere:

    use strict; use warnings; sub loop_over_hash { my( $keys, $href ) = @_; print join( ',', @$keys , $href ), "\n" and return unless 'HASH' e +q ref $href; loop_over_hash( [ @$keys, $_ ], $href->{$_} ) for keys %$href; } my %hash = ( a => { 1 => { x => 5, y => 6 }, 2 => { s => 7, t => 8 } }, b => { 3 => 'end', }, ); loop_over_hash [], \%hash;
Re: Hash with three keys
by toolic (Bishop) on Dec 12, 2013 at 21:07 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1066916]
Approved by toolic
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2024-04-25 18:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found