For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > November 2006 > sorting a hash - by data instead of key









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author sorting a hash - by data instead of key
Mike

2006-11-03, 6:57 pm

I was hoping someone could help me with a little Perl sorting problem.
I have a hash called %hostlist which is keyed by DNS 'hostname' and has
the data 'hostname|IP' (eg 'mike.net mike.net|192.168.13.1'). I'd like
to be able to sort the list based on the IP address, rather than the
key. The other little technicality is that the IP address sometimes
contains multiple values such as 192.168.13.1|192.168.14.1. I would
only care to sort based on the first value though.

I typically use the sort function below to sort by IP address, when the
IP address is the key, but I don't know what to do in this situation.
Can anyone help?

sub sortfunc
{
my @alist = split(/\./, $a);
my @blist = split(/\./, $b);

my $aval = 0;
my $bval = 0;
for (my $index = 0; $index <= 3; $index++)
{
$aval += $alist[$index] << ((3 - $index) * 8);
$bval += $blist[$index] << ((3 - $index) * 8);
}

return $aval <=> $bval;
}

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com