Sorting in Perl II (Schwartzian Transform)

By Andrew Johnson, ITworld |  How-to

The
three steps above can be combined by simply passing the results of the
preprocessing stage directly into the sort stage and passing those
results through the post-processing stage and out into our sorted array:

#!/usr/bin/perl -w
use strict;
my @data = ;
my @sorted = map { $_->[0] }
sort custom
map { [$_, split /:/ ] } @data;
print @sorted;

sub custom {
$a->[3] cmp $b->[3];
}
__DATA__
foo:23:bar:2.1
bar:42:qux:3.0
baz:19:foo:1.1
aux:19:foo:1.2

This 'map/sort/map' algorithm, referred to as the ST, provides a nice
clean and relatively efficient way to sort on computed or extracted
fields. We can also easily adjust our custom() comparison routine to
sort on multiple fields as shown in last week

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

ITworld Answers helps you solve problems and share expertise. Ask a question or take a crack at answering the new questions below.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question
randomness