John wrote:

Thanks for pointing out the indexing mistake. I've fixed that in the code
below, but the sorting is still correct. (I've also added "return 0" in
case $z is always 0, but I get the same sort results with or without it.)
The new array being sorted also shows that undef isn't sorted as if it's
0, since it comes before the -1. I'm trying to sort the arrays
lexicographically--and I'm succeeding,

perldoc perlop
[ SNIP ]
       Binary "<=>" returns -1, 0, or 1 depending on whether the left
       argument is numerically less than, equal to, or greater than the
       right argument.
[ SNIP ]
       Binary "cmp" returns -1, 0, or 1 depending on whether the left
       argument is stringwise less than, equal to, or greater than the
       right argument.

You say "lexicographically" but you are using a numerical comparison operator.


but I'm not sure why, without
running "for" for the length of the longer of the two arrays. Why this
works is really my question, and the reason I'm not using the strict
pragma.

'strict' won't complain about using 'undef' in a comparison, but 'warnings' will. But you could silence that warning inside the scope of the subroutine with:

no warnings 'uninitialized';


@array = ([2,2],[2],[2,1],[1],[1,2],[1,-1]);

sub test_sort {
    for (0..$#$a) {
        $z=$$a[$_]<=>$$b[$_];
        return $z if $z!=0
    }
    return 0
}

print "$$_[0],$$_[1]\n" for sort test_sort @array;

Do all of your arrays only have one or two elements? Or is this just an example?



John
--
Any intelligent fool can make things bigger and
more complex... It takes a touch of genius -
and a lot of courage to move in the opposite
direction.                   -- Albert Einstein

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to