I have an array of arrays that I want to sort. Each element of array A is an array with 3 elements. Array A looks like:

my @A = ([2,3,1], [1,2,3], [1,0,2], [3,1,2], [2,2,4]);

I want to sort A in ascending order. When comparing 2 elements, the first number is used. If there is a tie, the second number is used, and then the third number.

Here is my code. I use a function 'cmpfunc' to compare 2 elements.

sub cmpfunc {
    return ($a->[0] <=> $b->[0]) or 
           ($a->[1] <=> $b->[1]) or
           ($a->[2] <=> $b->[2]);
}
my @B = sort cmpfunc @A;
print "Result:\n";
for my $element (@B) {
    print join(",", @{$element}) . "\n";
}

Result:

1,2,3
1,0,2
2,3,1
2,2,4
3,1,2

The result is somewhat sorted, but not correct. What I expect is:

1,0,2
1,2,3
2,2,4
2,3,1
3,1,2

Is there any error in my comparison function? The strange thing is, when I put the comparison code in block, the result is correctly sorted.

my @C = sort { ($a->[0] <=> $b->[0]) or 
               ($a->[1] <=> $b->[1]) or
               ($a->[2] <=> $b->[2]) } @A;
Edit
Report