develooper Front page | perl.perl5.porters | Postings from October 2005

[perl #36430] Sort within a sort does not set $a, $b

Thread Previous
From:
Guest via RT
Date:
October 26, 2005 01:15
Subject:
[perl #36430] Sort within a sort does not set $a, $b
Message ID:
rt-3.0.11-36430-123303.2.91036563932153@perl.org
> [btilly@gmail.com - Wed Jun 29 17:56:08 2005]:
> If a sort happens while a sort is happening, $a and $b are not set.
> A co-worker ran into this on Perl 5.8.7.  The original example was a
> lot more complex, but here is a toy example that demonstrates the
> problem.
> 
>   #! /usr/bin/perl
>   use strict;
>   use Data::Dumper;
> 
>   my @list = sort { A::min(@$a) <=> A::min(@$b) }
>     [3, 1, 5],
>     [2, 4],
>     [0];
> 
>   print Dumper(\@list);
> 
>   package A;
>   sub min {
>     my @list = sort {
>       print STDERR "No \$a\n" unless defined($a);
>       print STDERR "No \$b\n" unless defined($b);
>       $a <=> $b;
>     } @_;
>     $list[0];
>   }

I think this is a duplicate of bug 7063, and the problem is actually
caused by the fact that the sort() is in a different package from the
sort sub.

I know how to fix it, but I'm slightly concerned that people might be
relying on the existing (mis)behaviour, which is that $a and $b are set
in the package that the sort is called from instead of the package where
the comparison sub lives.

(The existing behaviour does seem to be accidental. The code looks as
though it intends to use the package of the comparison routine, but gets
it a bit wrong.)

Robin

Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About