in reply to Re^2: beginner - ordering tuples
in thread beginner - ordering tuples

do you mind if I simplify it to a one liner?

use strict; use warnings; my @datas; # for (<DATA>){ # push @datas, [ m/<(\d+),(\d+)>/ ]; # } @datas = sort { $a->[0] <=> $b->[0] || $a->[1] <=> $b->[1] } map { [ m/<(\d+),(\d+)>/ ] } <DATA>; use Data::Dumper; print Dumper \@datas; __DATA__ <7,22> <12,20> <7,15> <1,5> <7,10>

please see sort about how the boolean three states condition decides about the ordering.

the perlop || is - like in C - short circuiting, that is the RHS is only evaluated (and returned) when the LHS is false (i.e 0 if <=> compares equal values).

If your tuples have more than 2 elements you should ask for a generic solution.

Cheers Rolf

Replies are listed 'Best First'.
Re^4: beginner - ordering tuples
by 7stud (Deacon) on Nov 13, 2010 at 22:19 UTC

    In your elegant solution, you need to switch around your second conditional to:

    $b->[1] <=> $a[1]
      Right, I missed that the second position should be descending.

      You forgot a dereferencing: $b->[1] <=> $a->[1]

      Cheers Rolf