xesecre has asked for the wisdom of the Perl Monks concerning the following question:

I have a question for the Wise Perl Monks, thanks in advance. I am using map and sort to sort by 2 columns. The trouble I am having is, it does sort the first column but it will not sort by any other column when I change the number. The list has numbers to sort. This is delimited by tab. What am I doing wrong?

my @sorted = map {$_->[0]} sort { $a->[0] <=> $b->[0] || sort { $a->[1] <=> $b->[1] } map {chomp;[$_,split(/\t/)]} <FILE>; print OUT "$_\n" for @sorted;

Replies are listed 'Best First'.
Re: Perl sort
by Corion (Patriarch) on Apr 26, 2016 at 14:30 UTC

    You are calling sort twice, which makes little sense. Also, your code does not even compile.

    Most likely you wanted something like:

    my @sorted = map {$_->[0]} sort { $a->[0] <=> $b->[0] || $a->[1] <=> $b->[1] } map {chomp;[$_,split(/\t/)]} <FILE>; print OUT "$_\n" for @sorted;
Re: Perl sort
by Laurent_R (Canon) on Apr 26, 2016 at 20:28 UTC
    In addition to the error pointed by Corion, I don't think you are trying to sort with the right items in the array reference you are building.

    Assuming one line of your file contains something like:

    12\t45
    your first map:
    map {chomp;[$_,split(/\t/)]}
    will transform this line into:
    ["12\t45", 12, 45]
    With such data, comparing:
    $a->[0] <=> $b->[0] || $a->[1] <=> $b->[1]
    in your sort code block makes little sense.

    I would assume you probably want something like:

    $a->[1] <=> $b->[1] or $a->[2] <=> $b->[2]