On Sat, Jun 02, 2001 at 06:13:04PM +1000, iain truskett wrote:
> Rob talked about
> 
> foreach $value(sort {$a <=> $b} (values(%hash)) {
>     print $value;
> }
> 
> vs.
> 
> foreach $value(sort byNum (values(%hash)) {
>     print $value;
> }
> 
> sub byNum {
>     $a <=> $b;
> }
> 
> 
> Am I correct in thinking that the anonymous subroutine is vaguely more
> efficient?
> 

I'm really not sure. It probably all depends. I'm not guru enough to
know all the ins and outs of efficiency. I would guess, though, that if
you have a fairly complex sort routine that you want to use a number of
times, it might be more efficient to compile it just once.

Mainly, I think it's a readability thing. Using {$a <=> $b} inline is
easier for maintenance than naming a routine, then having to go find it 
and see what it does. On the other hand, if you had a sort routine
something like the one below, that would be a bit of a pain to code
inline as an anonymous sub. And you could debug it as a named sub at
just the one place in the code.

sub byIP
{
        @a = split(/\./, $a);
        @b = split(/\./, $b);
        ($a[0] <=> $b[0]) ||
        ($a[1] <=> $b[1]) ||
        ($a[2] <=> $b[2]) ||
        ($a[3] <=> $b[3]);
}

cheers
rob c

Reply via email to