title: Using Constants in Perl
body: <p>I am trying to define constants in Perl using the <code>constant</code> pragma:</p>
  
  <pre><code>use constant {
      FOO =&gt; "bar",
      BAR =&gt; "foo"
  };
  </code></pre>
  
  <p>I'm running into a bit of trouble, and hoping there's a standard way of handling it.</p>
  
  <p>First of all...</p>
  
  <p>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.</p>
  
  <p>Most of this package will have constants involved in it:</p>
  
  <pre><code> print "This is my program";
  
   package MyClass;
  
   use constant {
      FOO =&gt; "bar"
   };
  
   sub new { ... }
  </code></pre>
  
  <p>I would like my constant <code>FOO</code> to be accessible to my main program. I would like to do this without having to refer to it as <code>MyClass::FOO</code>. Normally, when the package is a separate file, I could do this in my main program:</p>
  
  <pre><code>use MyClass qw(FOO);
  </code></pre>
  
  <p>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?</p>
  
  <p>The second issue...</p>
  
  <p>I would like to use the constant values as hash keys:</p>
  
  <pre><code>$myHash{FOO} = "bar";
  </code></pre>
  
  <p>The problem is that <code>%myHash</code> has the literal string <code>FOO</code> as the key and not the value of the constant. This causes problems when I do things like this:</p>
  
  <pre><code>if (defined $myHash{FOO}) {
     print "Key " . FOO . " does exist!\n";
  }
  </code></pre>
  
  <p>I could force the context:</p>
  
  <pre><code>if (defined $myHash{"" . FOO . ""}) {
  </code></pre>
  
  <p>I could add parentheses:</p>
  
  <pre><code>if (defined $myHash{FOO()}) {
  </code></pre>
  
  <p>Or, I could use a temporary variable:</p>
  
  <pre><code>my $foo = FOO;
  if (defined $myHash{$foo}) {
  </code></pre>
  
  <p>None of these are really nice ways of handling this issue. So, what is the best way? Is there one way I'm missing?</p>
  
  <p>By the way, I don't want to use <code>Readonly::Scalar</code> 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.</p>