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


in reply to Better way to define global variables

G'day govindkailas,

It's generally not a good idea to export by default (i.e. with @EXPORT) — see the Exporter documentation sections: Selecting What to Export and What Not to Export. Instead, consider using @EXPORT_OK and %EXPORT_TAGS.

Here's an example of Utilities.pm that does that:

package Utilities; use strict; use warnings; use Exporter qw{import}; my @sys_exports = qw{$SYS_DIR $SYS_OTHER}; my @util_exports = qw{$UTIL_THIS $UTIL_THAT}; our @EXPORT_OK = (@sys_exports, @util_exports); our %EXPORT_TAGS = (SYS => [@sys_exports], UTIL => [@util_exports]); our $SYS_DIR = "sys_dir"; our $SYS_OTHER = "sys_other"; our $UTIL_THIS = "util_this"; our $UTIL_THAT = "util_that"; 1;

Here's some sample runs showing how to use it.

No namespace pollution unless specifically requested:

$ perl -Mstrict -Mwarnings -E ' use Utilities; say $SYS_DIR; ' Global symbol "$SYS_DIR" requires explicit package name at -e line 3. Execution of -e aborted due to compilation errors.

Request a specific item:

$ perl -Mstrict -Mwarnings -E ' use Utilities qw{$SYS_DIR}; say $SYS_DIR; ' sys_dir

Request multiple items using a tag:

$ perl -Mstrict -Mwarnings -E ' use Utilities qw{:SYS}; say $SYS_DIR; ' sys_dir

Mix specific and tag requests:

$ perl -Mstrict -Mwarnings -E ' use Utilities qw{:UTIL $SYS_OTHER}; say $SYS_OTHER; say $UTIL_THAT; ' sys_other util_that

-- Ken