John wrote:
I'm sorting arrays by comparing corresponding entries.  Take this example:


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

sub my_sort {
    for (0...@$a) {

You have an off-by-one error because @$a is the number of elements in @$a, not the last index of @$a. That should be:

     for ( 0 .. $#$a ) {


        return $x if 0!=($x=$$a[$_]<=>$$b[$_])

You are returning $x if $a->[$_] is not equal to $b->[$_], but if $a->[$_] *is* *equal* *to* $b->[$_] you are returning what?

What exactly are you trying to accomplish with that?


    }
}

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


First I thought I needed "for" to run from 0 to the larger of the lengths
of @$a and @$b, but with the example code, Perl sorts the entries
correctly, even though "for" in &my_sort runs only to the last index of
@$a (which might be shorter than @$b).

Actually, it runs one past the last index of @$a if all the elements of @$a and @$b are equal.


I'd think that Perl would not know
how to sort a pair when $a is [2] and $b is [2,1], since it only compares
their first entries. It should get the right order when $b is [2] and $a
is [2,1], though, since "for" would run from 0 to 1. Does anyone know if
this example just happens to work, or does this always happen because of
the way Perl sorts things?

It appears that you are not using the 'warnings' and 'strict' pragmas because an array element that has not been defined yet will return the value 'undef' which will evaluate to 0 in a numerical comparison.



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