sorting - I want to sort array of arrays in Perl, but the result is not sorted -



sorting - I want to sort array of arrays in Perl, but the result is not sorted -

i have array of arrays want sort. each element of array array 3 elements. array looks like:

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

i want sort in ascending order. when comparing 2 elements, first number used. if there tie, sec number used, , 3rd number.

here code. utilize function 'cmpfunc' compare 2 elements.

sub cmpfunc { homecoming ($a->[0] <=> $b->[0]) or ($a->[1] <=> $b->[1]) or ($a->[2] <=> $b->[2]); } @b = sort cmpfunc @a; print "result:\n"; $element (@b) { print join(",", @{$element}) . "\n"; }

result:

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

the result sorted, not correct. expect is:

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

is there error in comparing function? unusual thing is, when set comparing code in block, result correctly sorted.

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

you executing

return ($a->[0] <=> $b->[0])

which returns before gets of "or" clauses.

either remove "return" keyword, or add together paranthesis around entire arg list return:

sub cmpfunc { return(($a->[0] <=> $b->[0]) or ($a->[1] <=> $b->[1]) or ($a->[2] <=> $b->[2])); }

perl sorting

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -