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

Yet another subtle bug in sort()

From:
Robin Houston
Date:
October 25, 2005 11:33
Subject:
Yet another subtle bug in sort()
Message ID:
20051025183259.GA28325@rpc142.cs.man.ac.uk
 sub foo{
     my $n = shift;
     if (!defined($n)) {  # No arg means we're being called by sort()
         return 1;
     }

     warn "in : n=$n\n";

     if ($n<5) {
         foo($n+1);
     }
     else {
          () = sort foo 1,2;
     }

     warn "out: n=$n\n";
 }

 foo(1);


This prints:

 in : n=1
 in : n=2
 in : n=3
 in : n=4
 in : n=5
 out: n=5
 out: n=4
 out: n=3
 out: n=2
 out: n=
 
Note the missing '1' at the end. You can see more clearly what's
happening if you suppress the clearance of $n on sub exit:

 sub foo{
     my $n if 0;
     $n = shift;
     if (!defined($n)) {  # No arg means we're being called by sort()
         $n = "No one will ever see this!";
         return 1;
     }
   [... same as before ...]

prints:

 in : n=1
 [...]
 out: n=2
 out: n=No one will ever see this!


Fortunately I think I know why this is happening and how to fix it.

I'm not surprised that no one has noticed it before: how often do
you call sort with a sort sub that's already active?
 
Robin



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