perl: inter-module variable use

只谈情不闲聊 提交于 2019-12-02 15:30:32

问题


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.



来源:https://stackoverflow.com/questions/11957621/perl-inter-module-variable-use

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!