Well, you can't sort a hash, as hashes are always unsorted. But presuming that you want to process the hash values in sorted order, you can do something like this:
foreach (sort ipsort keys %ip) { # each sorted key will be in $_ } sub ipsort { my @a = split /\./, $a; my @b = split /\./, $b; return $a[0] <=> $b[0] || $a[1] <=> $b[1] || $a[2] <=> $b[2] || $a[3] <=> $b[3]; }
Update: As hakkr points out below you can certainly have a variable that looks and acts like a sorted hash by using Tie::IxHash. But being pedantic, it isn't actually a hash. It's a Perl object (actually a reference to an array) that you can interact with via an interface that looks very much like a hash :)
And, anyway, it sorts by insertion order, which isn't what the OP wanted.
--"The first rule of Perl club is you do not talk about
Perl club."
-- Chip Salzenberg
In reply to Re: Sorting a hash of IP addresses?
by davorg
in thread Sorting a hash of IP addresses?
by mnperez
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |