Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re: Sort hash with values

by Preceptor (Deacon)
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 = ( "" => "UEH1_system_ip", "" => "UEH11_system_ip", "" => "UEH25_system_ip", "" => "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" => "" , "UEH11_system_ip" => "", "UEH25_system_ip" => "", "UEH111_system_ip" => "", ); 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 = '' UEH11_system_ip System_ip = '' UEH25_system_ip System_ip = '' UEH111_system_ip System_ip = ''

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1040328]
[1nickt]: So decadent, I love it! "Frequently bought together ..." the biscuits *and* the spread ;-)
[virtualsue]: we had it in belgium a few years ago then realised you could buy it everywhere in the uk

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (10)
As of 2017-11-20 11:59 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (286 votes). Check out past polls.