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

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.


Comment on Re: Accessing hash values in a HOH
Select or Download Code
Re^2: Accessing hash values in a HOH
by Athanasius (Monsignor) 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

    Output:

    16:53 >perl 545_SoPW.pl 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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (8)
As of 2014-10-25 18:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (147 votes), past polls