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

With constants, I can test that one is defined, or use it trivially:

   use constant FOO => 42;
   print defined(FOO);
   print FOO;
Now, if I have the name of the constant stored in a string:
   $var = "FOO";
how can I operate on $var to find out if the constant stored in it's name is defined, and what it's value is?

If I'm understanding what I've read, it may not be possible... but if it is, I'd like to know how.

Thanks

Replies are listed 'Best First'.
Re: Constant name stored in a string
by WizardOfUz (Friar) on Jan 28, 2010 at 14:25 UTC
    use constant FOO => 42; my $var = 'FOO'; print &{$var} . "\n"; print defined( &{$var} ) ? "true\n" : "false\n";

    Result:

    # 42 # true

    But this is a bad idea, on many levels ...

Re: Constant name stored in a string
by umasuresh (Hermit) on Jan 28, 2010 at 15:17 UTC
    According to Damian Conway using Readonly module is a better way of defining constants. See the following post by Randal Schwartz.
     http://www.stonehenge.com/merlyn/UnixReview/col65.html
Re: Constant name stored in a string
by JavaFan (Canon) on Jan 28, 2010 at 15:33 UTC
    That's not trivial. Defining a constant using the constant pragma means a subroutine with that name is created - a subroutine without a prototype.

    Now, it's fairly easy to test if there's a subroutine defined given a name, and it's also fairly easy to see whether it has an empty prototype. But not every function with an empty prototype is a constant.

    So, you may have to resort to introspection tools like Devel::Peek. It's Dump function can tell whether a subroutine is a constant - look for the CONST flag. Dump writes to STDERR, so if you want to do this from within your program, you may want to redirect STDERR and capture it yourself.

      Or you could examine %constant::declared.