如何设置类似 Java 的“静态变量"?在其他类可以访问的 Perl 中? [英] How can I set a Java-like "static variable" in Perl that can be accessed by other classes ?

查看:28
本文介绍了如何设置类似 Java 的“静态变量"?在其他类可以访问的 Perl 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类,比如 A 和 B,我需要在 A 类中设置一个静态变量(如 Java 中的静态变量),并从 B 类中访问该变量(在 Java 中使用 ClassName.variable 名称).我可以在 Perl 中做这样的事情吗.

I have two classes say A and B, i need to set a static variable in Class A (like static variables in Java ), and access the variable from class B (using ClassName.variable name in Java ). Can i do something like this in Perl .

提前致谢

推荐答案

我真的不懂 Java 所以我猜你说的静态变量"是什么意思?与范围界定有关吗?在 perl 中,我的"和我们的"是您可以控制范围的方式,但我相信我说帽子包/模块使变量的范围私有"是正确的.到 .pm 文件中声明它们(更正此和/或详细说明其他 perlistas!).

I don't know Java really so I'm guessing that what you mean by "static variable" is something to do with scoping? In perl 'my' and 'our' are the ways you can control scope, but I believe I am correct in saying hat packages/modules make variable's scope "private" to the .pm file they are declared in (correct this and/or elaborate further fellow perlistas!).

至于如何访问"嗯,我的 Programming Perl(第二版) 副本在第 2 章的作用域声明部分涵盖了这一点.但这是第 107 页第一个脚注的精辟(略有编辑)部分:

As for how to "access" them hmm my copy of Programming Perl (2nd Edition) covers this in chapter 2 in the section on Scoped Declarations. But here's a pithy (slightly edited) part of the first footnote from page 107:

库、模块和类使用包来存储它们自己的私有数据,因此它不会与主程序中的数据发生冲突.如果您看到有人编写 $Some::stuff,他们使用的是 Some 包中的 $stuff 标量变量.

Packages are used by libraries, modules, and classes to store their own private data so it doesn't conflict with data in your main program. If you see someone write $Some::stuff they're using the $stuff scalar variable from the package Some.

Exporter 文档和这个 perlmonks node 关于全局变量 可能会帮助您更清晰地思考 perl 中的变量和作用域.经典的 perlmonks 节点 - Perl 中的变量作用域:基础- 是经常查阅的参考资料:-)

The Exporter documentation and this perlmonks node about global variables might help you get clearer in your thinking about variables and scope in perl. The classic perlmonks node - Variable Scoping in Perl: the basics - is a frequently consulted reference :-)

如果您已经知道如何编程(即在 Java 中),有时还有另一个关于如何"的很好的参考(只是略有过时);在 Perl 中做事是Perl 手册 - 您可以在网上找到其中的摘录.

If you already know how to program (i.e. in Java) sometimes another good reference (only slightly dated) for "how to" do things in Perl is The Perl Cookbook - excerpts of which you can find online.

干杯,

这篇关于如何设置类似 Java 的“静态变量"?在其他类可以访问的 Perl 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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