Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

perl - How to make a hash available in another module

for Ex : 
package test1 ; 

my %hash = ( a=> 10 , b => 30 ) ;

1;

in Script : 

use test1 ;

print %hash ;  # How to  make this avilable in script without sub
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Good programming practice prescribes that you do not allow foreign code to mess with a module's data directly, instead they must go through an intermediary, for example an accessor routine.

TIMTOWTDI, with and without exporting. The Moose example appears quite long, but this one also allows setting data as opposed to just reading it from Test1, where the other three examples would need quite some additional code to handle this case.


unsugared

Module

package Test1;
{
    my %hash = (a => 10, b => 30);
    sub member_data { return %hash; }
}
1;

Program

use Test1 qw();
Test1::member_data; # returns (a => 10, b => 30)

Moose

Module

package Test1;
use Moose;
has 'member_data' => (is => 'rw', isa => 'HashRef', default => sub { return {a => 10, b => 30}; });
1;

Program

use Test1 qw();
Test1->new->member_data; # returns {a => 10, b => 30}
# can also set/write data!  ->member_data(\%something_new)

Sub::Exporter

Module

package Test1;
use Sub::Exporter -setup => { exports => [ qw(member_data) ] };

{
    my %hash = (a => 10, b => 30);
    sub member_data { return %hash; }
}
1;

Program

use Test1 qw(member_data);
member_data; # returns (a => 10, b => 30)

Exporter

Module

package Test1;
use parent 'Exporter';

our @EXPORT_OK = qw(member_data);

{
    my %hash = (a => 10, b => 30);
    sub member_data { return %hash; }
}
1;

Program

use Test1 qw(member_data);
member_data; # returns (a => 10, b => 30)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...