Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Arrays & Hashes

by Bugorr (Novice)
on Aug 18, 2005 at 18:45 UTC ( #484917=perlquestion: print w/ replies, xml ) Need Help??
Bugorr has asked for the wisdom of the Perl Monks concerning the following question:

Is that possible to create a hash and each element in this hash would be an array. If there's what is the way to access elements of array? Thank you. Little Update: It gets a little more complicated: I need to read a file which has: email\tdomain email\tdomain I would like to create a hash with keys that are domains and emails part of array of different domains.

Comment on Arrays & Hashes
Replies are listed 'Best First'.
Re: Arrays & Hashes
by friedo (Prior) on Aug 18, 2005 at 18:48 UTC
    You can create hashes of arrayrefs easily:

    my %hash = ( foo => [ 0,1,2 ], bar => [ 7,8,9 ] );

    To access individual elements:

    my $element = $hash{foo}[2];

    For more, see perldsc.

Re: Arrays & Hashes
by Zaxo (Archbishop) on Aug 18, 2005 at 18:51 UTC

    Certainly, make the hash values be references to arrays. We call that a HoA.

    my %hoa = ( alpha => ['A' .. 'Z','a' .. 'z'], numeric => [0 .. 9], );
    You can get at the array elements with multiple indexing: my $char = $hoa{'alpha'}[42];
    See perldsc and perllol for more on perl's deeper data structures.

    After Compline,
    Zaxo

Re: Arrays & Hashes
by Transient (Hermit) on Aug 18, 2005 at 18:51 UTC
    No, but you can create a hash of array refs...

    see perlref and perlreftut.

    Here's an example:
    my $hash_of_arrays = { array1 => [ 1, 2, 3 ], array2 => [ 'a', 'b', 'c' ] }; foreach my $key ( %$hash_of_arrays ) { print "Key: $key\n"; foreach my $array_element ( @$key ) { print "Array Element: $array_element\n"; } }
    (Untested)
Re: Arrays & Hashes
by artist (Parson) on Aug 18, 2005 at 19:33 UTC
    use Data::Dumper; while(<DATA>){ chomp; my ($email,$domain) = split /\t/; push @{$hash{$domain}},$email; } print join "\n", keys %hash,"\n"; print "Email:",$hash{'yahoo.com'}[0].'@yahoo.com'; __DATA__ ahlnpstx gmail.com dghjklorsvwy hotmail.com cdegijlmqrstvwxz yahoo.com abegijknostv yahoo.com abcefghjlqrtuyz hotmail.com acghiknoprux hotmail.com abceghlmrstwxy gmail.com cdehiklmnqtwxyz gmail.com bdjklmortvw hotmail.com bdegjkmrsuxz gmail.com
    --Artist

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (6)
As of 2015-08-01 01:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (285 votes), past polls