laziness, impatience, and hubris PerlMonks

### Answer: How do I write my own sorting routine?

by gam3 (Curate)
 on Mar 26, 2005 at 01:36 UTC Need Help??

Q&A > sorting > How do I write my own sorting routine? - Answer contributed by gam3

This seems like it is begging for a schwartzian transform.
```    my %engr_scale = (
k => 10**3,
m => 10**6,
g => 10**9,
t => 10**12,
);

sub normalized_net_speed {
local \$_ = lc shift;
s/^T1\b/1.544 mbps/i;
s/^([.0-9]+)\s*([kmgt])bps/ int( \$1 * \$engr_scale{lc \$2} ) /e;
s/[^.0-9].*\$//; # kill non-numeric stuff
\$_
}

my @sorted =
map  { \$_->[0] }
sort { \$a->[1] <=> \$b->[1] }
map  { [ \$_, normalized_net_speed(\$_) ] }
@array;

Replies are listed 'Best First'.
Re: Answer: How do I write my own sorting routine?
by tlm (Prior) on Mar 26, 2005 at 03:50 UTC

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:

```my \$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;
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 form
```{    \$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:

```{
mbps => 10**6,
kbps => 10**3,
bps  => 10**0,
},
{ 't1 line' => 100000 }
are created and destroyed anew with every iteration, for no good reason. Again, I see no reason not to simply write:
```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

Create A New User
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2018-01-18 09:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
How did you see in the new year?

Results (208 votes). Check out past polls.

Notices?