Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

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.

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,

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"; } }
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{''}[0].''; __DATA__ ahlnpstx dghjklorsvwy cdegijlmqrstvwxz abegijknostv abcefghjlqrtuyz acghiknoprux abceghlmrstwxy cdehiklmnqtwxyz bdjklmortvw bdegjkmrsuxz

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://484917]
Approved by friedo
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (9)
As of 2017-10-19 22:03 GMT
Find Nodes?
    Voting Booth?
    My fridge is mostly full of:

    Results (257 votes). Check out past polls.