Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: Accessing hash values in a HOH

by space_monk (Chaplain)
on Feb 23, 2013 at 06:34 UTC ( #1020278=note: print w/replies, xml ) Need Help??

in reply to Accessing hash values in a HOH

As previous poster has indicated, a hash of arrays appears to be what you want....
my % phoneDirectory=( 'Shirley'=> [ '555-0001', '555-0002' ], 'Michael' => [ 555-MIKE' ], 'Fred' => [ '555-FRED'] ); #access numbers for Shirley say $_ for @{$hash{'Shirley'}};
As to your second question, something like:
my %names; while (<>) { my ($first, $last) = split; if ($last) { # add last name to hash element push @{$names{$first}}, $last; } } # print names print @{$names{'John'}};

Caveat: Just taking a break from XCOM, have not compiled or tested above, so send me a message if syntax not quite right and I'll fix it :-)

Updated with comments from Athanasius below..

A Monk aims to give answers to those who have none, and to learn from those who know more.

Replies are listed 'Best First'.
Re^2: Accessing hash values in a HOH
by Athanasius (Chancellor) on Feb 23, 2013 at 07:04 UTC

    A couple of points:

    1. Don’t use first as the name of both the hash and the scalar! Yes, Perl can easily disambiguate them, but why make things harder (for humans) to read and comprehend than they need to be?

    2. The line:

      $first{$first} = [] if (!$first{$first});

      isn’t needed — autovivification will take care of that for you automatically.

    #! perl use strict; use warnings; my %names; while (<DATA>) { my ($first, $last) = split; push @{$names{$first}}, $last if $last; } my $name_to_find = 'John'; print "$name_to_find --> ", join(', ', @{$names{$name_to_find}}), "\n" +; __DATA__ John Marry John Lea John Paul David Patrik David Sam


    16:53 >perl John --> Marry, Lea, Paul 16:56 >

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re^2: Accessing hash values in a HOH
by modi2020 (Novice) on Feb 23, 2013 at 16:06 UTC
    Thank you so much! Worked like charm! Best wishes

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1020278]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2018-05-26 12:55 GMT
Find Nodes?
    Voting Booth?