Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Sort hash with values

by Preceptor (Deacon)
on Jun 23, 2013 at 15:19 UTC ( [id://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'

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (7)
As of 2024-04-23 08:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found