在 Perl 中,如何从库导入哈希?
我有一个文件 revs.pm
:
my %vers = ( foo => "bar" );
另一个文件如 importer.pl
:
use revs;
如何从 importer.pl 访问
%vers
?
I have a file revs.pm
:
my %vers = ( foo => "bar" );
And another file like importer.pl
:
use revs;
How can I access %vers
from importer.pl
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
创建适当的模块并将 my 关键字更改为 我们的:
Create a proper module and change the my keyword to our:
另一种传统方法是在 package,并导出变量:
这避免了在从
importer.pl 引用变量时必须使用包名称
:一个缺点是您必须确保变量名称是唯一的,以避免名称冲突。
Another conventional way is to use the Exporter module in your package, and export the variable:
This avoids having to use the package name when referring to the variable from
importer.pl
:One disadvantage is that you must make sure your variable name is unique in order to avoid name collisions.
或者,您可以不将程序的某些部分与
全局变量。考虑一下当您在一个模块中使用此哈希时会发生什么:
然后在其他某个模块中:
然后使用这两个模块:
根据
$some_condition
,some_other_function 会产生不同的结果每次调用时都会得到结果。祝调试愉快。 (这是
更多的是
每个
问题而不是全局状态问题;但通过暴露在内部实现中,您允许调用者执行以下操作
你不是故意的,这很容易破坏你的程序。)
当你改变硬编码时,重写 Foo 和 Bar 也是一件痛苦的事情
例如,哈希到按需数据库查找。
所以真正的解决方案是设计一个合适的 API,并将其导出
而不是整个变量:
现在你的模块更容易使用:
现在 some_function 不能搞乱 some_other_function,当你
更改 get_component_version 的实现,其余的
程序不会关心。
Alternatively, you could just not couple parts of your program with a
global variable. Consider what happens when you use this hash in one module:
And then in some other module:
And then use both modules:
Depending on
$some_condition
, some_other_function produces differentresults each time you call it. Have fun debugging that. (This is
more of an
each
problem than a global state problem; but by exposingthe internal implementation, you allow your callers to do things that
you didn't intend, and that can easily break your program.)
It's also a pain to rewrite Foo and Bar when you change the hard-coded
hash to an on-demand database lookup, for example.
So the real solution is to design a proper API, and export that
instead of the entire variable:
Now your module is easier to use:
Now some_function can't mess up some_other_function, and when you
change the implementation of get_component_version, the rest of your
program won't care.