Perl 模块中的作用域如何工作?

发布于 2024-09-01 12:09:15 字数 160 浏览 2 评论 0 原文

我不太明白 Perl 模块中的作用域是如何工作的。这不会打印任何内容。我希望运行 a.pl 打印 1

b.pm

$f=1;

a.pl

use b;

print $f

I don't really understand how scoping works in Perl modules. This doesn't print anything. I would like it if running a.pl printed 1

b.pm

$f=1;

a.pl

use b;

print $f

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

薄荷梦 2024-09-08 12:09:15

好吧,您有很多误解,我们可以通过解决您眼前的问题并为您提供良好的资源来最好地解决这些误解。

b.pm 应该是:

package b;
our $f = 1;
1;

a.pl 应该

use b;
print $b::f

使用 perl -I 运行整个过程。 a.pl

现在去阅读 perldocperlmod非常仔细。

另请阅读 perldocstrict

OK, you have a lot of misconceptions that we can best address by fixing your immediate problem and pointing you to good resources.

b.pm should be:

package b;
our $f = 1;
1;

a.pl should be

use b;
print $b::f

run the whole thing with perl -I. a.pl

Now go read perldocperlmod very carefully.

Also read perldocstrict.

诠释孤独 2024-09-08 12:09:15

您应该首先阅读手册中有关 Perl 模块的内容:在命令行中使用 perldoc perlmod,或者转到 http://perldoc.perl.org/perlmod.html

You should start off by reading about Perl modules in the manual: perldoc perlmod at the commandline, or go to http://perldoc.perl.org/perlmod.html.

三生一梦 2024-09-08 12:09:15

简短回答:很可能是因为您在不区分大小写的文件系统上运行此代码,其中请求模块 b 会加载内置模块 B。您的模块根本没有被加载。如果重命名 b,您将得到预期的结果。

较长的答案包括许多因未能遵守哪怕是最起码的良好实践而受到的责备,并且已被删除。

Short answer: Most probably because you're running this code on a case-insensitive file system, where asking for the module b loads the built-in module B. Your module is not getting loaded at all. If you rename b, you get the result you expect.

The longer answer included lots of chiding for failing to observe even minimal good practice, and has been elided.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文