mikfire has asked for the wisdom of the Perl Monks concerning the following question:

What, with one thing and another, I found myself abusing constant.pm today - I am in need of mneumonic return codes and this struck me as the most likely way to proceed. I wonder, though, what kind of performance penalty the Constant Functions ( cf ) would be imposing.

Is there a Monk present who could provide me enlightenment on this topic? If constant.pm is considering odious, is there another way of accomplishing the same end? I really need the mneumonic codes, but I am open to alternate ideas.

Mik
mikfire

PS - Yes, I have already thought of using a hash to hold the return codes and returning the correct codes from there, eg, return $ERROR_CODE{NO_ERROR}; I just liked the way it read with constants better, eg, return NO_ERROR;

Replies are listed 'Best First'.
Re: Constant Functions
by Adam (Vicar) on May 24, 2000 at 02:01 UTC
    Actually constant.pm has very little overhead. It just declares your constants as functions (within the correct namespace even) which return their constant value. Perl is slick enough to inline these, so your only overhead is pulling in the extra module. You can eliminate this by doing it by hand, if you really feel the need.

    The simple way then is too just declare the funcs your self, thusly:sub C() { 299792458 } # Meters/Second

      I was just thinking about this, and a neat idea popped into my head: I gave the speed of light as my example, but I gave it in meters per second. What if I wanted to store that value in a couple formats? I could name it C_MPS or something equivalently useless, but I like simple straight forward names. So I started thinking about namespaces. You could put your collection of constants into a package and then name each function with an appropriate moniker. Don't export any of them, just reference them directly... ie, C::MPS and C::MPH and so on. I suppose you get fancy and write the function C to return C::MPS (or your prefered default) and Export that. Then the user can just call C or C::YPD (yards per day) And since Perl will inline each constant function, you still don't take any usage hit.
      A reply falls below the community's threshold of quality. You may see it by logging in.