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

Hi monks, I'm trying to access a .pm file containing constants (as in "use constant XX => 1;") from two other files by putting a "use Constants" at the top of each. However, one of the two files uses the other one as well and Perl complains about whichever one uses the constants second. i.e. if in file A.pm I have:
use B; use Constants;
then the interpreter complains about constants in A but not B. if I have instead
use Constants; use B;
then it complains about constants in B. Questions:
1) What gives?
2) Is this the best way to use constants across multiple files?

UPDATE: I think export will do it. Thanks!

Replies are listed 'Best First'.
Re: Using constants in multiple files?
by ikegami (Patriarch) on Oct 06, 2005 at 21:42 UTC

    Does Constants use package? If not, you should be using do, not use:

    A.pm ---- # Order doesn't matter. BEGIN { do 'Constants.pm' } use B;
    B.pm ---- BEGIN { do 'Constants.pm' }

    use will only run the module once.

    If Constants uses package, then Constants must export the constants:

    A.pm ---- # Order doesn't matter. use Constants; use B;
    B.pm ---- use Constants;
Re: Using constants in multiple files?
by ambrus (Abbot) on Oct 06, 2005 at 21:06 UTC

    Try putting use Constants; in the beginning of the A module. Update: I mean in the beginning of both your A and B modules.

    (I hope you don't really use B as a module name, as it's used up.)

    Update: Your problem might also be that you don't have a package declaration in the Constants module, so the constants get defined in the wrong package (A or B). Also you'll have to Export the constants from the Constants module if you want to use them without a package prefix.

Re: Using constants in multiple files?
by Zaxo (Archbishop) on Oct 06, 2005 at 21:15 UTC

    In addition to what ambrus says, you can import the constants you want with,

    # in A.pm package A; use Constants qw(XX);
    which will alias A::XX() to Constants::XX(). XX() may then be used in package A without a fully qualified name.

    After Compline,
    Zaxo