开发者

Export a hash from a module to a script

开发者 https://www.devze.com 2023-02-10 18:54 出处:网络
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.

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.


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:

 return \%debug_hash;

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. :)

0

精彩评论

暂无评论...
验证码 换一张
取 消