Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Hash in Perl

by Athanasius (Archbishop)
on Jan 02, 2014 at 06:35 UTC ( [id://1068901]=note: print w/replies, xml ) Need Help??


in reply to Hash in Perl

Create a second hash, with countries as the keys; the hash value for each country will be an anonymous array containing the cities belonging to that country:

#! perl use strict; use warnings; my %h1 = ( 'Chicago, USA' => undef, 'Frankfurt, Germany' => undef, 'Berlin, Germany' => undef, 'Washington, USA' => undef, 'Helsinki, Finland' => undef, 'New York, USA' => undef, ); my %h2; for (keys %h1) { my ($city, $country) = split ', '; push @{ $h2{$country} }, $city; } for (sort keys %h2) { print "$_: ", join(', ', sort { $a cmp $b } @{ $h2{$_} }), "\n"; }

Output:

16:29 >perl 819_SoPW.pl Finland: Helsinki Germany: Berlin, Frankfurt USA: Chicago, New York, Washington 16:31 >

Note: Perl autovivifies the new $h2{$country} elements as needed.

Hope that helps,

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

Replies are listed 'Best First'.
Re^2: Hash in Perl
by rammohan (Acolyte) on Jan 02, 2014 at 06:41 UTC
    why you again declare undef function.Actually we declare all values in hash then we need again that undef.?
      ... we declare all values in hash ...

      Declare them as what? As Anonymous Monk pointed out above, the data you show is not a hash, it’s a list (of strings). Since you said this data is in a hash, I made a guess as to how the hash was contstructed. A hash is a collection of key/value pairs. Every key must have a value (and every value must belong to a key). I assumed that the data was stored as hash keys, so I supplied an undef value for each — but that could have been any value, as it isn’t used.

      If your hash is really key/value pairs of the form: Chicago => 'USA' (another guess), adapting the answer I gave above should be quite straightforward.

      Hope that helps,

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

        Thank you well explanation.
        my%hash = (Script => "Perl", script_1=>"Ruby", script_2=> "PHP"); for my$k (keys %{my$href}) { print "$k => ${$href}{$k}\n"; }
        it showing Global symbol $href requires explicit package name.why this error.?

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2024-04-26 02:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found