Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

question on constants

by smackdab (Pilgrim)
on Jan 01, 2002 at 08:08 UTC ( #135489=perlquestion: print w/ replies, xml ) Need Help??
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

Comment on question on constants
Select or Download Code
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!)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://135489]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (11)
As of 2014-08-27 21:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (253 votes), past polls