[NTLUG:Discuss] Sort question

Patrick R. Michaud pmichaud at pobox.com
Thu Apr 5 15:15:43 CDT 2012


On Thu, Apr 05, 2012 at 06:40:29AM -0700, Fred wrote:
> I have a long table with 6 columns of numbers. I want each row of 6 numbers to 
> 
> be arranged in ascending order and separated by some delimiter such as
> comma or space, like this:
> 
> 53 17 3 24 9 33 
> 
> 16 8 42 29 1 20
> <etc>
> 
> would become
> 
> 3 9 17 24 33 53
> 1 8 16 20 29 42
> <etc>
> [...]
> Any suggestions?

This is probably not that helpful in your case (because Perl 6 is not yet
that common in Linux distributions), but in Perl 6 the answer is a one-liner:

    $ cat data.txt
    53 17 3 24 9 33
    16 8 42 29 1 20

    $ ./perl6 -e 'for "data.txt".IO.lines { .split(" ").sort(+*).say }'
    3 9 17 24 33 53
    1 8 16 20 29 42

Or if you prefer list comprehensions:

    $ ./perl6 -e '.split(" ").sort(+*).say for "data.txt".IO.lines'
    3 9 17 24 33 53
    1 8 16 20 29 42

Or to let Perl 6 do the looping for you:

    $ ./perl6 -n -e '.split(" ").sort(+*).say' data.txt
    3 9 17 24 33 53
    1 8 16 20 29 42

Explanation:
    .split(" ")  splits each input line by spaces into a list
    .sort(+*) sorts the elements of the list numerically
    .say prints the sorted list to standard output

Pm



More information about the Discuss mailing list