Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Sort hash with values

by Cristoforo (Deacon)
on Jun 24, 2013 at 02:34 UTC ( #1040348=note: print w/ replies, xml ) Need Help??


in reply to Sort hash with values

An approach using Socket's inet_aton and inet_ntoa to sort the ips.

#!/usr/bin/perl use strict; use warnings; use Socket qw /inet_aton inet_ntoa/; my %ip_store = ( "11.0.0.1" => "UEH1_system_ip", "11.0.0.11" => "UEH11_system_ip", "11.0.0.3" => "UEH25_system_ip", "11.0.0.25" => "UEH111_system_ip" ); my @sorted = map {inet_ntoa $_} sort map {inet_aton $_} keys %ip_store +; foreach my $ip (@sorted) { print "$ip\n"; print "System_ip = '$ip_store{$ip}' \n"; }
Output:
C:\Old_Data\perlp>perl t9.pl 11.0.0.1 System_ip = 'UEH1_system_ip' 11.0.0.3 System_ip = 'UEH25_system_ip' 11.0.0.11 System_ip = 'UEH11_system_ip' 11.0.0.25 System_ip = 'UEH111_system_ip'
Chris


Comment on Re: Sort hash with values
Select or Download Code
Re^2: Sort hash with values
by sammy_01 (Initiate) on Jun 24, 2013 at 06:36 UTC
    Hi Rahul,

    May be this will solve your problem.

    sub mySort { $a =~ /(\d+)/; my $firstVal = $1; $b =~ /(\d+)/; my $secVal = $1; $firstVal <=> $secVal; } my %IP_Store = ( "11.0.0.1" => "UEH1_system_ip", "11.0.0.11" => "UEH11_system_ip", "11.0.0.3" => "UEH25_system_ip", "11.0.0.25" => "UEH111_system_ip" ); %new_hash = reverse(%IP_Store); foreach my $key (sort mySort (keys(%new_hash))) { chomp($key); print "$key\n"; print "System_ip = $new_hash{$key}\n"; #print "PDN-IP = '$Values' \n"; }
    The only change i have done is reversing the hash.

    Output:

    -------

    UEH1_system_ip

    System_ip = 11.0.0.1

    UEH11_system_ip

    System_ip = 11.0.0.11

    UEH25_system_ip

    System_ip = 11.0.0.3

    UEH111_system_ip

    System_ip = 11.0.0.25

      The only change i have done is reversing the hash.

      A naive hash reversal works just fine if the hash values are unique to begin with. If they're not, somebody's gonna get (silently) clobbered. Maybe add a pre/post reversal size check:

      >perl -wMstrict -le "my %hash = qw(a aye b bee c see eh aye); ;; my $pre_k = keys %hash; %hash = reverse %hash; $pre_k == keys %hash or die 'somebody got clobbered'; " somebody got clobbered at -e line 1.
        Oh Yes, i do agree with you.
        Sammy..

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (12)
As of 2014-07-23 10:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (139 votes), past polls