[Durham] another sort question - numbers in slashes

Martin Ward martin at gkc.org.uk
Fri Nov 8 12:01:47 UTC 2013


On Tuesday 05 Nov 2013 at 15:28, Dougie Nisbet <dougie at highmoor.co.uk> wrote:
> switch1  1/0/18  192.etc etc etc etc
> switch1  1/0/4  192.etc etc etc etc
> switch1  1/0/5  192.etc etc etc etc
> 
> I can't work out how to sort on the switchname and numerically sort on the
> switchport. I don't know what I'm missing, but I'm missing it, whatever it
> is.

Sounds like a job for a Schwartzian transform
http://en.wikipedia.org/wiki/Schwartzian_transform

#!/usr/bin/perl

use strict;
use warnings;

print map  { $_->[0] }
      sort { $a->[1] cmp $b->[1] }
      map  { [ $_, padded($_) ] }
      <>;

sub padded($) {
  my ($str) = @_;
  $str =~ s#(\d+)/(\d+)/(\d+)
           #join("/", map { sprintf("%02i", $_) } ($1, $2, $3))#xe;
  return($str);
}

####################################

The function "padded" zero-pads each of the three switchport numbers
to two digits, then we sort on the padded string but print 
the original string.

-- 
			Martin

Dr Martin Ward STRL Principal Lecturer and Reader in Software Engineering
martin at gkc.org.uk  http://www.cse.dmu.ac.uk/~mward/  Erdos number: 4
G.K.Chesterton web site: http://www.cse.dmu.ac.uk/~mward/gkc/
Mirrors:  http://www.gkc.org.uk  and  http://www.gkc.org.uk/gkc



More information about the Durham mailing list