Skip to content

Instantly share code, notes, and snippets.

@soren
Created March 19, 2021 07:44

Revisions

  1. soren created this gist Mar 19, 2021.
    46 changes: 46 additions & 0 deletions schwartzian_transform.pl
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    #!/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);