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
+3
source share
3 answers

Good programming practice prescribes that you do not allow the external code to directly communicate with the module data, instead they must go through an intermediary, for example, an access procedure.

TIMTOWTDI, with and without export. The Moose example looks pretty long, but it also allows you to set data, rather than just reading it from Test1, where the other three examples will require 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)
+14
source

, . our, my, script , : %test1::hash.

, Exporter.

# The module.
package Bubb;

use strict;
use warnings;

use base qw(Exporter); # As of Perl 5.10: `use parent ...`

our @EXPORT_OK = qw(bar %fubb);

sub bar { 'bar' }

our %fubb = (fizz => 1, buzz => 2);

1;

# The script.
use Bubb qw(bar %fubb);

, , .

# The module.
# Basically the same as above, except this:
our @EXPORT_OK = qw(bar fubb);

sub fubb {
    return fizz => 1, buzz => 2;
}

# The script.
use Bubb qw(bar fubb);

my %fubb = fubb();
+6

First of all, you cannot declare it with "my", as this declares lexical, not batch, variables. Use ourso that you can reference the package variable and assign it the required value. Then in your other package, the prefix is ​​the name of the variable with the name of the first package. usenot like the C # operator using, since it does not import characters from another package, it just makes them available.

Something like this should work to demonstrate:

use strict;
use warnings;

package test1; 

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

package test2;

print $test1::hash{a} ; #prints 10
+5
source

Source: https://habr.com/ru/post/1751557/


All Articles