http://www.perlmonks.org?node_id=1040328


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'