Convert Schwartz to 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 a head or tail.

+6
source share
2 answers

Read from bottom to top:

 @array 

Array (from file names, followed by use).

 map [$_,-s $_], 

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

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

Sort the list of array links by increasing the file size.

 map $_->[0], 

Turn the list of array references back to the list of file names, but now in sorted order.

 my @output = 

Save the list to @output.

This is equivalent to the function:

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

but it only gets the size for each file once instead of one comparison made by sorting.

+10
source

Wikipedia has a detailed explanation and analysis.

+4
source

Source: https://habr.com/ru/post/891384/


All Articles