'Perl: How to use constant defined in other pl file from a strict perl file?

We have some perl files in strict mode and some not. Some constants (global variables) are defined in a perl library (.pl) in non-strict mode, for example "$XXXX = '....';".

When I tried working on a perl file in strict mode to use such constant/global variable (defined in the non-strict mode perl file), I got a compilation error "Global symbol "$XXXX" requires explicit package name".

I am kind of new to perl. So far it seems to me that package is only available in perl module (.pm) and I cannot add a package to a perl library (.pl) file, is it right?

I guess the best way is to put all constants in a module, but then this requires changing all the files that use constant. Right now we prefer a minimum number of file change. I wonder if there are other ways to work around it while keeping the original strict or non-strict mode?



Solution 1:[1]

This is (partly) what Exporter is for.

In MyConsts.pm:

package MyConsts;

use strict;
use warnings;

# Load the Exporter module
use parent 'Exporter';

# Define the symbols that will be exported
our @EXPORT = qw($Important_Constant);

# Declare and set the variables.
# Note that they must be *package* variables
# (so use "our", not "my")
our $Important_Constant = 10;

1;

In a program:

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use MyConsts;

say $Important_Constant;

Solution 2:[2]

Just citing from man constant (Perl 5.26.1):

       Constants belong to the package they are defined in.  To refer to a
       constant defined in another package, specify the full package name, as
       in "Some::Package::CONSTANT".  Constants may be exported by modules,
       and may also be called as either class or instance methods, that is, as
       "Some::Package->CONSTANT" or as "$obj->CONSTANT" where $obj is an
       instance of "Some::Package".  Subclasses may define their own constants
       to override those in their base class.

       As of version 1.32 of this module, constants can be defined in packages
       other than the caller, by including the package name in the name of the
       constant:

           use constant "OtherPackage::FWIBBLE" => 7865;
           constant->import("Other::FWOBBLE",$value); # dynamically at run time

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ikegami
Solution 2 U. Windl