in reply to Re: Sorting question
in thread Sorting question
In this case it's unlikely to matter, but the sort subroutines are closures which means that they'll remember $ref and $a/$b will be package variables of the package in which the subroutines are defined. That means that if the subroutines are used in a sort in another package, the wrong $a/$b variables will be used. In order to solves that the ($$) prototype has special meaning. With that prototype $a and $b will be passed to the subroutine, and you use $_[0] and $_[1] instead:
An example:sub ($$) { $ref->{$_[0]} <=> $ref->{$_[1]} }
This becomes useful (necessary) if the sort routines are abstracted further.use strict; no warnings; # So many that they hide the output. { package Foo; sub doit { my ($sorter, @keys) = @_; return sort $sorter @keys; } } my @foo = (3, 1, 2); print '$a: ', join(' ', Foo::doit(sub { $a <=> $b }, @foo)), "\n"; print '@_: ', join(' ', Foo::doit(sub ($$) { $_[0] <=> $_[1] }, @foo)) +, "\n"; __END__ $a: 3 1 2 @_: 1 2 3
Update: Fixed several typos.
lodin
|
|---|