in reply to Re: How do I write my own sorting routine?
in thread How do I write my own sorting routine?
I think the common practice of shoving the "key extraction" routine of the ST right into the first map scares away many a novice. There is no shame, especially if one aims to instruct, in writing something like:
Once the code for the extraction routine is pulled out of the map/sort/map sequence what is left is not only very easy to follow, but, more importantly, it shows the essential structure of the ST, making it obvious that most of it is pretty generic. The most significant source of variation left is the nature of the sort routine, but with a well thought-out $extract function, the sort routine can often be reduced to the general formmy $extract = sub { my $x = lc($_[0]); if ($x =~ s/^(\d+)\s*//) { $x = $1 * { mbps => 10**6, kbps => 10**3, bps => 10**0, }->{$x}; } else { $x = { 't1 line' => 100000 }->{$x}; } die "Bad input $_[0]" unless $x; return $x; }; my @sorted = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map [ $_, $extract->( $_ ) ], @array;
{ $a->[1] <=> $b->[1] or $b->[2] <=> $a->[2] or $a->[3] cmp $b->[3] # ...compare as many sort keys as you please }
Incidentally, it seems to me very much contrary to the spirit of the ST, a little perverse even, to have unnecessarily repetitious code in the extraction routine. The constant anonymous hashes:
are created and destroyed anew with every iteration, for no good reason. Again, I see no reason not to simply write:{ mbps => 10**6, kbps => 10**3, bps => 10**0, }, { 't1 line' => 100000 }
my %lookup = ( mbps => 10**6, kbps => 10**3, bps => 10**0, 't1 line' => 100000 ); my $extract = sub { my $x = lc($_[0]); if ($x =~ s/^(\d+)\s*//) { $x = $1 * $lookup{ $x }; } else { $x = $lookup{ $x }; } die "Bad input $_[0]" unless $x; return $x; }; # etc.
the lowliest monk
|
|---|