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

Say I define a bunch of constants in a perl script, lets call it globals.pl, and I want to use them in another perl script. Constants defined like: use constant ERROR => 1; require "globals.pl"; doesn't seem to do it, although it has no problem importing variables and functions, but it won't import constants.
  • Comment on How to import constants from another perl script

Replies are listed 'Best First'.
Re: How to import constants from another perl script
by Anonymous Monk on Nov 01, 2010 at 03:35 UTC
    Yes it will, see Simple Module Tutorial
    $ cat connie.pl use constant PI => 4 * atan2(1, 1); use constant DEBUG => 0; 1; $ perl -e"require q!connie.pl!; warn PI; PI at -e line 1. $ perl -e"require q!connie.pl!; warn PI(); 3.14159265358979 at -e line 1. $ perl -e"BEGIN{ require q!connie.pl!;} warn PI; 3.14159265358979 at -e line 1.
Re: How to import constants from another perl script
by kcott (Archbishop) on Nov 01, 2010 at 03:47 UTC

    We'd really need to see the code in order to explain what is or isn't happening.

    Having said that, it would be better to put them in a separate module file (e.g. MyConstants.pm) then use MyConstants;. This allows you to use your constants in whatever scripts you want without polluting your namespace with whatever else is in globals.pl.

    You can then make a decision whether you want to export the constants automatically (not generally recommended), export them on request (a much better alternative) or you can access them by name (e.g. MyConstants::ERROR).

    Here's some doco that may help: constant, Const::Fast, Readonly and Exporter.

    -- Ken

      Alright the first reply appears to be correct, it seems my problem was not appending () to the end of the constant in order to print the value. Why is this necessary in script where it was not defined but not in the one it was defined?
        because if you don't have a BEGIN { } block around the require, the constants will be loaded at runtime. In other words, they aren't yet known at compile time of the script. Adding parens in this case is a hint to the compiler that the constants are subroutines (which they internally are), not barewords.