Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Sort hash with values

by Preceptor (Chaplain)
on Jun 23, 2013 at 15:19 UTC ( #1040328=note: print w/ replies, xml ) Need Help??


in reply to Sort hash with values

You have your keys and values backwards in your hash. Your code prints (sorted) list of values. And then you try and access the hash using that value, which simply isn't going to work.

Try instead:

use strict; use warnings; 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" ); sub mySort { $IP_Store{$a} =~ /(\d+)/; my $firstVal = $1; $IP_Store{$b} =~ /(\d+)/; my $secVal = $1; $firstVal <=> $secVal; } foreach my $Value (sort mySort (keys (%IP_Store))) { print "$IP_Store{$Value}\n"; print "System_ip = '$Value' \n"; #print "PDN-IP = '$Values' \n"; }

The problem you've got is you grab the values out of the hash, and sort them into order. But at that point, you no longer have they key that references that value.

An alternative would be to swap around the keys and values in your hash, e.g.:

use strict; use warnings; my %IP_Store = ( "UEH1_system_ip" => "11.0.0.1" , "UEH11_system_ip" => "11.0.0.11", "UEH25_system_ip" => "11.0.0.3", "UEH111_system_ip" => "11.0.0.25", ); sub mySort { $a =~ /(\d+)/; my $firstVal = $1; $b =~ /(\d+)/; my $secVal = $1; $firstVal <=> $secVal; } foreach my $Value (sort mySort (keys (%IP_Store))) { print "$Value\n"; print "System_ip = '$IP_Store{$Value}' \n"; #print "PDN-IP = '$Values' \n"; }

This gives the same output each time, which is:

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'


Comment on Re: Sort hash with values
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (13)
As of 2014-10-23 19:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (128 votes), past polls