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

Hash of Hashes of Arrays

by Miguel (Friar)
on Jan 11, 2005 at 01:43 UTC ( #421167=perlquestion: print w/ replies, xml ) Need Help??
Miguel has asked for the wisdom of the Perl Monks concerning the following question:

Esteemed Monks,

This is a simple (perhaps, dumb) question, but how do I convert a List of Lists like This:

my @AoA = ( [qw/10 27 17 20/], [qw/10 24 22 25/], [qw/11 25 24 25/], [qw/11 26 19 20/], )

into an Hash of Hashes of Arrays like this:

my %HoH = ( 10 => { 27 => [17 .. 20], 24 => [22 .. 25], }, 11 => { 25 => [24 .. 25], 26 => [19 .. 20], } );

where the first column is the key of the first Hash and the second column is the key of the second hash?

TIA,
Miguel

Comment on Hash of Hashes of Arrays
Select or Download Code
Re: Hash of Hashes of Arrays
by Ovid (Cardinal) on Jan 11, 2005 at 01:52 UTC

    Well, I noticed that in your %HoH, you're using a range operator for the array ref. Assuming your really do want a range and that the 3rd and 4th values are always in the correct order, you can do this:

    #!/usr/local/bin/perl use strict; use warnings; use Data::Dumper; $Data::Dumper::Indent = 1; my @AoA = ( [qw/10 27 17 20/], [qw/10 24 22 25/], [qw/11 25 24 25/], [qw/11 26 19 20/], ); my %HoH; foreach my $aref (@AoA) { my ($key1, $key2) = splice @$aref => 0, 2; @$aref = $aref->[0] .. $aref->[1]; # this creates the range $HoH{$key1}{$key2} = $aref; } print Dumper \%HoH;

    If the range operator was a typo, you can delete the line I marked with the comment. If the order of the 3rd and 4th elements are not guaranteed, then it's trivial to reverse 'em.

    Of course, depending on your data, you may or may not want sanity checking in there.

    Cheers,
    Ovid

    New address of my CGI Course.

      Thank you very much!

      The 3rd and 4th elements are always in the correct order. So no worries about that.

Re: Hash of Hashes of Arrays
by BrowserUk (Pope) on Jan 11, 2005 at 01:59 UTC

    my %HoH; $HoH{ $_->[ 0 ] }{ $_->[ 1 ] } = [ $_->[ 2 ] .. $_->[ 3 ] ] for @AoA;

    Examine what is said, not who speaks.
    Silence betokens consent.
    Love the truth but pardon error.
Re: Hash of Hashes of Arrays
by trammell (Priest) on Jan 11, 2005 at 02:00 UTC
    my %HoH; for (@AoA) { $HoH{ $_->[0] }{ $_->[1] } = [ $_->[2] .. $_->[3] ]; }

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2014-09-15 03:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (145 votes), past polls