本文介绍了如何使哈希在另一个模块中可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

良好的编程习惯规定,您不允许外来代码直接弄乱模块的数据,相反,它们必须经过中介程序(例如访问器例程).

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,带有或不带有导出. Moose示例看起来很长,但是与从Test1读取数据相反,该示例还允许设置数据,而其他三个示例将需要一些额外的代码来处理这种情况.

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.

模块

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

程序

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;

程序

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


Sub :: Exporter

模块


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;

程序

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;

程序

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

这篇关于如何使哈希在另一个模块中可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 21:13