in reply to The best way to use constants

Is using constants slower than using variables
Considering that Perl doesn't have constants, the question isn't clear. It will depend on what you consider a constant. Many people consider a variable in all caps to be a constant. That of course is as fast as using constants.

Others use "use constant" or tiny subs with an empty prototype returning a literal as constants. Are they faster than variables? Well, that depends. If it's just fetching a value (read access), yes, then they are faster as the fetch can be done at compile time. But such constants lack a sigil. So you cannot easily interpolate them. Hence, you might write:

printf "The value is %d.\n", CONSTANT;
instead of
print "The value is $CONSTANT.\n";
The former means parsing a format, and substituting. That may very well be slower than the interpolation.

Now, you are using methods as constants. I haven't benchmarked it, but I'd be quite surprised if that wasn't the slowest solution of the three (variable, empty prototype sub, method).

Personally, I prefer variable. In all caps. Speed difference isn't an issue for me. Variables interpolate; subs and methods don't. If I want to trap a possible assignment to such a variable, I use Readonly. But usually, I do not care. If someone wants to assign to something that's supposed to constant, it's their own responsibility. Who am I to stop them?

Replies are listed 'Best First'.
Re^2: The best way to use constants
by almut (Canon) on Apr 02, 2009 at 19:29 UTC
    If I want to trap a possible assignment to such a variable, I use Readonly.

    This comparison of Readonly against some alternatives (like Scalar::Readonly) might be of interest here.

      Thanks a lot guys for your viewpoints. Scalar::Readonly looks interesting and so does the idea of not using class methods and exporting the constants.