in reply to Re^2: Build Sort dynamically
in thread Build Sort dynamically

The not working correctly was an extra comma. Sorry for the typo, but as I said, all code is untested. I've removed that and it should work better.

The prototype is explained in the documentation to sort. If you provide the prototype, then the arguments are passed in @_. If you don't, then they are passed in $a and $b. Passing in $a and $b is marginally more efficient, but the problem comes when you create a sort routine in one package and call it in another. The package in which $a and $b are set is the one you call the sort routine in, and not the one you created the subs in. Which can become tricky. With the prototype, those cross-package problems go away.

This is potentially important in this case because depending on your overall code organization you may want to have each field know how to sort its own datatype. (Add a date-time field which could be in another language and it will quickly become apparent why you might want a more sophisticated organization.) Which would result in sort routines being spread out across packages.

Replies are listed 'Best First'.
Re^4: Build Sort dynamically
by AnomalousMonk (Archbishop) on Aug 24, 2008 at 07:33 UTC
    Ooo, neat! I tried my little test without the extraneous comma and it worked as advertised.

    I had thought the discussion regarding prototyping the subroutines supplied to sort applied only to named subroutines. This insight may come in very handy! Thanks for the tip. I will have to re-read the sort docs more closely (but tomorrow -- signing off soon).

    (Likewise, the discussion of prototyping in perlsub needs another perusal -- or is it perl-rusal?)

      What you need to know about prototyping in general is don't. Except when it does something really useful for you.

      The useful places are as follows. If you need to emulate a built-in, you have no choice but to prototype. If you want a constant to be optimized at compile time, you should use a prototype. (But constant does that for you.) The ($$) prototype is useful in sorting. And an & prototype can turn blocks into subroutines saving the need to type "sub ".

      Personally the only prototype that I have found useful in the last 2 years is putting ($$) on a sort routine.