On Wed, 15 Dec 2010 01:37:28 -0600, John W. Krahn <jwkr...@shaw.ca> wrote:
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
John,
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, 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.
@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;
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/