Export a hash from a module to a script

3.1k views Asked by At

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.

1

There are 1 answers

2
tchrist On BEST ANSWER

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