[aklug] Re: perl lists question, sorting, sort of.

From: Arthur Corliss <acorliss@nevaeh-linux.org>
Date: Tue Aug 17 2010 - 16:26:49 AKDT

On Tue, 17 Aug 2010, Michael Fowler wrote:

> inet_aton($a) cmp inet_aton($b) would be a simpler means of
> accomplishing the sort, though both are going to choke on IPv6
> addresses. What do you have against IPv6, Arthur?

If you're going to go that route you should be using <=> not cmp. You're
right, though, inet_aton is definitely shorter.

As for IPv6: it's a good idea poorly implemented and managed. I'll deal
with it when I have to, but not until then. :-)

> Comments and blank lines will also throw it a bit.
>
> Also, /sm? You have joined the cargo cult!

:-) I differ with Conway in several areas, but I can't fault his logic on
the regex bit.

> Columnated output, ordered by IPv4 address, followed by IPv6 addresses,
> with comments removed. IPv6 sorting could be improved with the addition
> of the Socket6 module, but that isn't core.
>
> It could be improved by reordering each cell by length, that way the
> columns are approximately equal in size.
>
> perl -MSocket=inet_aton -anwe '
> BEGIN { $maxcol = 0 }
>
> push @{ $ip{$F[0]} }, @F[1..$#F] unless /^\s*(#|$)/;
> $maxcol = @F if @F > $maxcol;
>
> END {
> @table = map { [$_, @{ $ip{$_} }] } keys %ip; # generate table
> foreach my $row (@table) {
> push @$row, ("") x ($maxcol - @$row); # pad the row
> foreach my $i (0 .. $#$row) {
> $maxlen[$i] = length $row->[$i]
> if not defined $maxlen[$i] or length $row->[$i] > $maxlen[$i];
> }
> }
>
> $format = join(" ", map { "%-" . $_ . "s" } @maxlen) . "\n";
> printf $format, @$_ for sort {
> my $ai = inet_aton($a->[0]);
> my $bi = inet_aton($b->[0]);
> return -1 if defined $ai and not defined $bi;
> return 1 if not defined $ai and defined $bi;
> return $a->[0] cmp $b->[0] if not defined $ai and not defined $bi;
> return $ai cmp $bi;
> } @table;
> }
> ' /etc/hosts

<Sheesh> You get points for completeness, but at some point that really
belongs in a script, not a one-liner! Man, I bet your history file is in
MB... ;-) Good show!

         --Arthur Corliss
           Live Free or Die
---------
To unsubscribe, send email to <aklug-request@aklug.org>
with 'unsubscribe' in the message body.
Received on Tue Aug 17 16:26:57 2010

This archive was generated by hypermail 2.1.8 : Tue Aug 17 2010 - 16:26:57 AKDT