mathog
mathog

Reputation: 345

perl declare and export variables from a module

I need to modify a bunch of scripts to do the equivalent of a straight C style "include" of a moderate number of variables. After the "use" to pull these in it should act exactly as if a line like this had been included:

my $os_name = "Windows"; #declares the variable AND sets its value

So that they may be used in the "calling" script. There is a little bit of logic in the module that conditionally sets the values of these variables. The scripts all have "use strict". A typical "caller" has:

use strict;
use File::Basename;
use lib dirname (__FILE__);
use os_specific;
print "DEBUG os_name $os_name\n";

and the module (os_specific.pm) has:

package os_specific;
use warnings;
use strict;
use Exporter;
our @EXPORT = qw($os_name);
our $os_name="Windows";
1

But it doesn't work, there are compile stage warnings like:

Global symbol "$os_name" requires explicit package name at caller.pl.

So the declaration of the variable in the module is not effective at the caller's scope.

Can this be done, or must each of these variables also be declared in caller.pl? (All responses please employ "use strict" - without that it can be done using a "require". That doesn't work with "use strict" though because it throws a compile time error.)

I know the variables from the module can be used as "$os_specific::os_name", the question is how to set this up so that they can be used as just "$os_name".

Thanks.

Upvotes: 3

Views: 6306

Answers (2)

Borodin
Borodin

Reputation: 126722

The problem is that you aren't inheriting any functionality from Exporter because you haven't set the @ISA package variable.

Your module should look like this, after fixing the package name (packages should use upper and lower case letters only, by convention) and should be in the file OSSpecific.pm

package OSSpecific;

use strict;
use warnings;

use Exporter;
our @ISA    = qw/ Exporter /;
our @EXPORT = qw/ $os_name /;

our $os_name = "Windows";

1;

Upvotes: 5

Miller
Miller

Reputation: 35198

You need an explicit import method in your package, as demonstrated in Exporter.

You also need to fix the casing of your package name, the filename, and your use statement so they all match.

OS_Specific.pm:

package OS_Specific;
use warnings;
use strict;
use Exporter qw(import);

And the other file:

use OS_Specific;

Check out perlstyle for useful guidelines on picking package names:

Perl informally reserves lowercase module names for "pragma" modules like integer and strict. Other modules should begin with a capital letter and use mixed case, but probably without underscores due to limitations in primitive file systems' representations of module names as files that must fit into a few sparse bytes.

Upvotes: 3

Related Questions