in reply to sorting /etc/hosts

Is this a trick?

updated to compensate for my foolish assumption.

use strict; my @lines=<DATA>; print sort{by_ip($a)<=>by_ip($b)} @lines; sub by_ip { @_[0]=~ /\.(\d+)\s/; return $1; } __DATA__ 10.194.196.55 heckyll 10.194.196.57 txwl013w 10.194.196.61 krios 10.194.196.62 stasis # dial up server 10.194.196.63 nnocdts01 # sparc 5 in wan rm 10.194.196.65 libra 10.194.196.66 legato-school 10.194.196.67 txwlxdbs nnocs002a 10.194.196.46 chqnocp01 # Laser 4MV by Joe Blow 10.194.196.47 chqnocp02 10.194.196.9 TEST 10.194.196.49 nnocrpt01 10.194.196.64 saturn 10.194.196.50 nnocgw001 10.194.196.52 nnocs002 10.194.196.53 wslkms02 wslknms0 10.194.196.54 nnocws001

Replies are listed 'Best First'.
Re: Re: sorting /etc/hosts (boo)
by kjherron (Pilgrim) on Aug 31, 2001 at 22:51 UTC
    Your example sorts lexically, not numerically. It'll sort 10.10.10.10 before 10.10.10.2, for example:
    my @lines=<DATA>; print sort @lines; __DATA__ 10.194.196.9 made-up 10.194.196.55 heckyll 10.194.196.57 txwl013w 10.194.196.61 krios 10.194.196.62 stasis # dial up server
    This sorts the "made-up" line to the end, whereas the original poster presumably would want it first.

    Like the other replies said, a numerical sort is more appropriate here. The number of "cycles" used either way is going to be pretty trivial.

Re: Re: sorting /etc/hosts (boo)
by Anonymous Monk on Aug 31, 2001 at 22:47 UTC
    add to your DATA: 10.194.196.9 nnocws001 10.194.196.100 nnocws001 and you'll see it's not quite so straight-forward. you're doing a sort based on "standard string comparison order", instead of numerical. though the OP doesn't specify.