Using Constants in Perl

Posted by David W. on Stack Overflow See other posts from Stack Overflow or by David W.
Published on 2010-06-16T20:44:15Z Indexed on 2010/06/16 20:52 UTC
Read the original article Hit count: 285

Filed under:
|

I am trying to define constants in Perl using the use Constant pragma:

use Constant {
    FOO => "bar",
    BAR => "foo"
};

I'm running into a bit of trouble, and hoping there's a standard way of handling it.

First of all...

I am defining a hook script for Subversion. To make things simple, I want to have a single file where the class (package) I'm using is in the same file as my actual script.

Most of this package will have constants involved in it:

 print "This is my program";

 package "MyClass";

 use constant {
    FOO => "bar"
 };

 sub new {
   yaddah, yaddah, yaddah.

I would like my constant FOO to be accessible to my main program. I would like to do this without having to refer to it as MyClass::FOO. Normally, when the package is a separate file, I could do this in my main program:

use MyClass qw(FOO);

but, since my class and program are a single file, I can't do that. What would be the best way for my main program to be able to access my constants defined in my class?

The second issue...

I would like to use the constant values as hash keys:

$myHash{FOO} = "bar";

The problem is that %myHash has the literal string FOO as the key and not the value of the constant. This causes problems when I do things like this:

if (defined($myHash{FOO})) {
   print "Key " . FOO . " does exist!\n";
}

I could force the context:

 if (defined("" . FOO . "")) {

I could add parentheses:

if (defined(FOO())) {

Or, I could use a temporary variable:

my $foo = FOO;
if (defined($foo)) {

None of these are really nice ways of handling this issue. So, what is the best way? Is there one way I'm missing?

By the way, I don't want to use Readonly::Scalar because it is 1). slow, and 2). not part of the standard Perl package. I want to define my hook not to require additional Perl packages and to be as simple as possible to work.

© Stack Overflow or respective owner

Related posts about perl

Related posts about constants