Created
March 19, 2021 07:44
-
-
Save soren/e907ea2f000c25d908c8f49e0919b95f to your computer and use it in GitHub Desktop.
Code from the column "Sorting with the Schwartzian Transform" published in "Unix Review" issue 64 (May 2006)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
# Based on code from http://www.stonehenge.com/merlyn/UnixReview/col64.html | |
use strict; | |
use warnings; | |
use Data::Dumper; | |
print "Input \$str\n"; | |
my $str = | |
"eir 11 9 2 6 3 1 1 81% 63% 13\n" . | |
"oos 10 6 4 3 3 0 4 60% 70% 25\n" . | |
"hrh 10 6 4 5 1 2 2 60% 70% 15\n" . | |
"spp 10 6 4 3 3 1 3 60% 60% 14\n"; | |
print Dumper($str); | |
print "\nSplit \$str into a list of lines\n"; | |
my @lines = split /\n/, $str; | |
print Dumper(\@lines); | |
print "\nMap lines plus extracted sort key into a list of arrayrefs\n"; | |
my @annotated_lines = map { [$_, (split)[-1]] } @lines; | |
print Dumper(\@annotated_lines); | |
print "\nSort lines using the sort key\n"; | |
my @sorted_lines = sort { $a->[1] <=> $b->[1] } @annotated_lines; | |
print Dumper(\@sorted_lines); | |
print "\nExtract lines, i.e. remove sort key\n"; | |
my @clean_lines = map { $_->[0] } @sorted_lines; | |
print Dumper(\@clean_lines); | |
print "\nCreate \$result string:\n"; | |
my $result = join "\n", @clean_lines; | |
print Dumper($result); | |
print "\n\nAll the above in one go using the Schwartzian Transform\n"; | |
my $result_using_schwartzian_transform = | |
join "\n", | |
map { $_->[0] } | |
sort { $a->[1] <=> $b->[1] } | |
map { [$_, (split)[-1]] } | |
split /\n/, | |
$str; | |
print Dumper($result_using_schwartzian_transform); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment