perl: inter-module variable use

2019-03-05 15:00发布

问题:

I have a module misc with variable $verbose:

use strict;
use diagnostics;
package misc;
my $verbose = 1;

and module mymod which uses misc:

use strict;
use diagnostics;
use misc;
package mymod;
sub mysub ($) {
  ...
  ($misc::verbose > 0) and print "verbose!\n";
}

which is, in turn, used by myprog:

use strict;
use diagnostics;
use misc;
use mymod;
mymod::mysub("foo");

when I execute myprog, I get this warning:

Use of uninitialized value $misc::verbose in numeric gt (>) at mymod.pm line ...

what am I doing wrong?

回答1:

In mymod.pm you should be using:

our $verbose = 1;

instead of:

my $verbose = 1;

The warning is because $misc::verbose tries to access the package variable $verbose in the misc package, which incidentally, is not declared.

The my function creates a lexically scoped variable. In this case, you require a package scoped variable, which is created by using the our function.

Please pay attention to daxim's comment.