Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

How do I make a hash of arrays?

by vroom (His Eminence)
on Jan 12, 2000 at 00:35 UTC ( [id://1977]=perlquestion: print w/replies, xml ) Need Help??

vroom has asked for the wisdom of the Perl Monks concerning the following question: (data structures)

How do I make a hash of arrays?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I make a hash of arrays?
by chromatic (Archbishop) on Apr 01, 2000 at 01:22 UTC
    my %dramatis_personae = ( humans => [ 'hamnet', 'shakespeare', 'robyn', ], faeries => [ 'oberon', 'titania', 'puck', ], other => [ 'morpheus, lord of dreams' ], );
    Access it like this:
    foreach my $group (keys %dramatis_personae) { print "The members of $group are\n"; foreach (@{$dramatis_personae{$group}}) { print "\t$_\n"; } }
Re: How do I make a hash of arrays?
by Anonymous Monk on Aug 16, 2004 at 21:19 UTC
    You can always...
    push(@{$hash{$key}}, $insert_val);

    ...to load the arrays in the hash. That way you don't have to build the arrays, then dereference them into the hash.
Re: How do I make a hash of arrays?
by Anonymous Monk on Jul 07, 2002 at 11:49 UTC
    my @arrayOne = 1..10; my @arrayTwo = 20..30; my %HashOfArrays = ( one => \@arrayOne ); $HashOfArrays{two} = \@arrayTwo; $HashOfArrays{IpointToTheSameArrayAsOne} = \@arrayOne ; $HashOfArrays{IreferenceTheSameArrayAsOne} = \@arrayOne ; $HashOfArrays{MyValueIsThatOfOneAsWell} = \@arrayOne ;
    ## to create an array reference, just type \@array
    ## or [ @array ]
    ##  [ @array ] does not equal \@array
    ## see perlref for more info
    
Re: How do I make a hash of arrays?
by Doraemon (Beadle) on May 11, 2004 at 12:38 UTC
    my $array = []; #create new anonymous array ref push (@$array, '11'); push (@$array, '12'); push (@$array, '13'); $hash{'first'} = $array; # add $array = []; #create a new anon-array push (@$array, '21'); push (@$array, '22'); push (@$array, '23'); $hash{'second'} = $array; # add print "Hash content\n"; foreach $k (keys %hash) { foreach (@{$hash{$k}}) { print " : $_"; } print "\n"; }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2025-06-20 07:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.