Final Virtusertable Perl Sort

As the final stage of the sorting posts, I’ve converted the original virtusertable sort to the ‘Schwartzian Transform’ with multiple sorts. Notice i create the ‘sub arrays’ with 3 items:

$_[0] = "user@domain <whitespace> target"
$_[1] = "domain"
$_[2] = "user"

I’ve submitted this script for testing by the ‘Shell Lord’ to see how it fares compared to the old one!

#! /usr/bin/perl -w

use strict;

if (! @ARGV){
        print " Usage: sort.pl \n";
        exit 1;
}

sub domain {
        my $addy = shift;
        $addy =~ /\@([^\s]*)\s+/;
        return $1;
}

sub user {
        my $addy = shift;
        $addy =~ /^([^\s]*)\@/;
        return $1;
}

my @virtusertable = grep(!/^###|^$/, <>);
my @sorted_virtusertable = map { $_->[0] } sort { $a->[1] cmp $b->[1] || $a->[2] cmp $b->[2] } map { [$_, &domain($_), &user($_)] } @virtusertable;
my $divider;
foreach (@sorted_virtusertable){
        if ( &domain($_) ne $divider){
                print "\n" . "#" x 60 . "\n";
                print "### " . &domain($_) . " " . "#" x (55 - length(&domain($_))) . "\n";
                print "#" x 60 . "\n";
                $divider = &domain($_);
        }
        print;
}

Enough sorting for now….

Timings as shown:

# New Script
real	0m0.038s
user	0m0.038s
sys	0m0.000s

#Old Script

real	0m0.071s
user	0m0.071s
sys	0m0.000s
This entry was posted in FreeBSD Administration, Perl and tagged , , , , . Bookmark the permalink.

Leave a Reply