Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Schwartzian transform in Perl?

Tags:

perl

my @output =
map $_->[0],
sort{$a->[1] <=> $b->[1]}
map [$_,-s $_],     
@array;   

Can someone explain the code in more detail? I can't get head or tail of it ..

like image 354
compile-fan Avatar asked Jun 26 '11 10:06

compile-fan


2 Answers

Read from the bottom up:

@array

An array (of filenames, given later usage).

map [$_,-s $_],

For each filename, get a reference to a two element anonymous array, with the first element being the filename and the second element, the byte size of the file. map returns a list of these array references.

sort{$a->[1] <=> $b->[1]}

Sort the list of array references by increasing file size.

map $_->[0],

Turn the list of array references back into a list of filenames, but now in sorted order.

my @output =

Save the list in @output.

This is equivalent in function to:

my @output = sort { -s $a <=> -s $b } @array;

but only gets the size for each file once instead of once per comparison done by the sort.

like image 107
ysth Avatar answered Sep 20 '22 23:09

ysth


Wikipedia has a detailed explanation and analysis

like image 31
Quentin Avatar answered Sep 21 '22 23:09

Quentin