On Wed, 15 Dec 2010 15:50:40 -0600, John W. Krahn <jwkr...@shaw.ca> wrote:

John wrote:
[ SNIP ]
You say "lexicographically" but you are using a numerical comparison operator.

I meant lexicographically in that the arrays should be sorted first by
comparing their first entries, then their second ones, etc.  In the
example, I'm using numbers, but the behavior is similar if I use letters
and cmp.

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?

This is just an example.  I saw this first in a script where I'm sorting
arrays of different lengths (and no predetermined max length).  I wanted
to see what would happen if I didn't run "for" through all the entries in
the larger of the two of $#$a and $#$b, and instead just to $#$a.  I was
surprised to see that it still came out with the right order.

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