ishii@hexard.co.jp (Koji Ishii) (10/28/90)
Larry said $a and $b in sort function is bound to current package
at PL#36. But it seems to have a bug, please look at package yy in
following sample. Here, $a and $b are not bound to package yy but
package xx.
I wonder why they are bound to such names as $a and $b, not to
$_[0] and $_[1]. This is the only case where perl requires special
names to programmers. Could you explain if I'm missing something?
hxrdgw:~/unnews/test[21]% perl28 sorttest.pl
28:1 4 5 9:
36:9 5 4 1:
28:1 4 5 9:
36:9 5 4 1:
XX:9 5 4 1:
hxrdgw:~/unnews/test[22]% perl sorttest.pl
28:9 5 4 1:
36:1 4 5 9:
28:9 5 4 1:
36:9 5 4 1:
XX:1 4 5 9:
#!/usr/bin/perl
&sorttest( 9, 5, 4, 1 );
&sorttest2( 9, 5, 4, 1 );
package xx;
sub numerical28 { $main'a - $main'b; }
sub numerical36 { $a - $b; }
sub main'sorttest {
local( @x ) = sort xx'numerical28 @_;
print "28:@x:\n";
@x = sort xx'numerical36 @_;
print "36:@x:\n";
}
package yy;
sub numerical28 { $main'a - $main'b; }
sub numerical36 { $a - $b; }
sub numerical36_bug { $xx'a - $xx'b; }
sub main'sorttest2 {
local( @x ) = sort yy'numerical28 @_;
print "28:@x:\n";
@x = sort yy'numerical36 @_;
print "36:@x:\n";
@x = sort yy'numerical36_bug @_;
print "XX:@x:\n";
}
--
----------------------------------
Koji Ishii Hexard Inc., Tokyo, Japan. JUNET: ishii@hexard.co.jplwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) (10/28/90)
In article <ISHII.90Oct28161346@hxrdgw.hexard.co.jp> ishii@hexard.co.jp (Koji Ishii) writes:
:
: Larry said $a and $b in sort function is bound to current package
: at PL#36. But it seems to have a bug, please look at package yy in
: following sample. Here, $a and $b are not bound to package yy but
: package xx.
Yep, it's a bug. It's binding to the $a and $b of the first package in
which a sort is called. The result of a bit of leftover code that
assumed that packages were purely lexical.
Well, hey, this is why it isn't version 4.0 yet...
: I wonder why they are bound to such names as $a and $b, not to
: $_[0] and $_[1]. This is the only case where perl requires special
: names to programmers. Could you explain if I'm missing something?
It's only for efficiency. It's more overhead to set up an array than
a couple of scalar variables and more overhead to dereference the array
elements once they're in the array, and since the sort routine gets called
very heavily, we compromise a little. Besides, it makes the sort routines
look almost algebraic. :-)
Larry