Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

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 = ''

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

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (12)
As of 2016-02-10 23:03 GMT
Find Nodes?
    Voting Booth?

    How many photographs, souvenirs, artworks, trophies or other decorative objects are displayed in your home?

    Results (354 votes), past polls