Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Accessing hash values in a HOH

by space_monk (Chaplain)
on Feb 23, 2013 at 06:34 UTC ( [id://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 (Archbishop) 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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1020278]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2024-03-19 04:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found