perl:模块间变量使用 [英] perl: inter-module variable use

查看:288
本文介绍了perl:模块间变量使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量为$verbose的模块misc:

I have a module misc with variable $verbose:

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

和使用misc的模块mymod:

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

依次由myprog使用:

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

当我执行myprog时,会收到以下警告:

when I execute myprog, I get this warning:

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

我在做什么错了?

推荐答案

mymod.pm中,您应该使用:

our $verbose = 1;

代替:

my $verbose = 1;

警告是因为$misc::verbose试图访问>程序包中的程序包变量 $verbose,但未声明.

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

my 函数创建一个词法范围变量.在这种情况下,您需要使用使用 our 函数.

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.

请注意 daxim 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆