http://www.perlmonks.org?node_id=135489

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

From PerlDoc:
"Symbols are package scoped. That is, you can refer to a constant in package Other as Other::CONST."

I defined:
use constant CFGDIR=>'/config/' in my main script
Then tried to refer to it from module1.pm, $c = main::CFGDIR
This didn't work for me. I switched it to a $variable, which did work, so I don't think it is a typo...
I saw a web site mention using "my", so I tried:
my constant CFGDIR=>'/config/' our constant CFGDIR=>'/config/'
thanks for any suggestions

Replies are listed 'Best First'.
Re: question on constants
by wog (Curate) on Jan 01, 2002 at 09:16 UTC

    My guess is that you were probably doing something like:

    use module_that_tries_to_use_the_constant; use constant CFGDIR=>'/config/';

    The problem with that is that perl tries to compile your module first, but doesn't know what main::CFGDIR is at the time since the use constant hasn't happened yet. You can probably get around this by putting the use constant before the other use or doing main::CFGDIR() in the module (this lets perl know that you're trying to call the function by that name; constants are really functions with a specific prototype).

    (I'm guessing here. Next time -- give an error message.)

    I would note that this is bad coding practice -- a module should be independent of the "main" program. You probably should be passing a configuration directory to the module, instead. (If you really need the speed boost constants give, then you can still get it this way by having this information be passed on the use line, and defining a constant within the module at compile-time based on that...)

      Thanks, I did find that putting a '&' infront of the constant, got it to work...I'll also move my config stuff into a module, so that I am not grabbing stuff from the main program...but I am a little lazy ;-) (at time, more than a little!)