将哈希值从模块导出到脚本
回顾这个线程,我正在挣扎以及如何从我的模块导出数据的方式。一种方法有效,但我想实施的另一种方法无效。
问题是为什么脚本中的第二种方法不起作用? (我没有 h2xs 模块,因为我猜这只是为了分发)
Perl 5.10/ Linux distro
Module my_common_declarations.pm
#!/usr/bin/perl -w
package my_common_declarations;
use strict;
use warnings;
use parent qw(Exporter);
our @EXPORT_OK = qw(debugme);
# local datas
my ( $tmp, $exec_mode, $DEBUGME );
my %debug_hash = ( true => 1, TRUE => 1, false => 0, FALSE => 0, tmp=>$tmp, exec=>$exec_mode, debugme=>$DEBUGME );
# exported hash
sub debugme {
return %debug_hash;
}
1;
Script
#!/usr/bin/perl -w
use strict;
use warnings;
use my_common_declarations qw(debugme);
# 1st Method: WORKS
my %local_hash = &debugme;
print "\n1st method:\nTRUE: ". $local_hash{true}. " ou : " . $local_hash{TRUE} , "\n";
# 2nd Method: CAVEATS
# error returned : "Global symbol "%debug_hash" requires explicit package name"
print "2nd method \n " . $debug_hash{true};
__END__
提前谢谢。
refering back to this thread, I'm strugglying with the way how to export datas from my module. One way is working but not the other one which I would like to implement.
The question is why the second method in the script is not working ?
(I did not h2xs the module as I guess this is for distributing only)
Perl 5.10/ Linux distro
Module my_common_declarations.pm
#!/usr/bin/perl -w
package my_common_declarations;
use strict;
use warnings;
use parent qw(Exporter);
our @EXPORT_OK = qw(debugme);
# local datas
my ( $tmp, $exec_mode, $DEBUGME );
my %debug_hash = ( true => 1, TRUE => 1, false => 0, FALSE => 0, tmp=>$tmp, exec=>$exec_mode, debugme=>$DEBUGME );
# exported hash
sub debugme {
return %debug_hash;
}
1;
Script
#!/usr/bin/perl -w
use strict;
use warnings;
use my_common_declarations qw(debugme);
# 1st Method: WORKS
my %local_hash = &debugme;
print "\n1st method:\nTRUE: ". $local_hash{true}. " ou : " . $local_hash{TRUE} , "\n";
# 2nd Method: CAVEATS
# error returned : "Global symbol "%debug_hash" requires explicit package name"
print "2nd method \n " . $debug_hash{true};
__END__
Thx in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您返回的不是哈希值,而是哈希值的副本。所有传入或传出函数的哈希值都会被分解为键值对列表。因此,有一份副本。
相反,返回对哈希值的引用:
但这会将您的内部结构暴露给外部世界。这不是一件很干净的事情。
您还可以将
%debug_hash
添加到您的@EXPORT
列表中,但这是一个更危险的事情。请只使用功能性界面,你不会后悔的——更重要的是,其他人也不会后悔。 :)You’re returning not a hash but rather a copy of the hash. All hashes passed into or out of a function get dehashed into a key-value pairlist. Hence, a copy.
Return a reference to the hash instead:
But this reveals your internals to the world outside. Not a very clean thing to do.
You could also add
%debug_hash
to your@EXPORT
list, but that’s an even dodgier thing to do. Please please please use a functional interface only, and you won’t regret it — and more importantly, neither shall anyone else. :)