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


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

sub my_sort {
        for (0...@$a) {
                return $x if 0!=($x=$$a[$_]<=>$$b[$_])
        }
}

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).  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?

Thanks,
John

--
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