in reply to Accessing the hash name in perl
As hippo said, your code goes about your task in an over-complicated way. Just load the library normally and call a function in it. ( See the monastery's Tutorials on modules. )
MyLib.pm :
my_script.pl :package MyLib; use strict; use warnings; sub get_data { my %hash = ( A => { a => 1, b => 2, }, B => { a => 3, b => 4, }, ); return \%hash; } 1;
use strict; use warnings; use MyLib; my $hashref = MyLib::get_data(); my %hash = %{ $hashref }; for my $key ( keys %hash ) { printf( 'Value of `a` in %s is %s', $key, $hash{ $key }->{'a'} ); } __END__
Or, use a data format suited to hashes:
my_data.yaml :
--- A: a: 1 b: 2 B: a: 3 b: 4
my_script2.pl :
use strict; use warnings; use YAML qw/ LoadFile /; my $hashref = LoadFile('my_data.yaml'); my %hash = %{ $hashref }; for my $key ( keys %hash ) { printf( "Value of `a` in %s is %s', $key, $hash{ $key }->{'a'} ); } __END__
Hope this helps!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Accessing the hash name in perl
by Sonali (Novice) on Mar 23, 2017 at 10:40 UTC | |
by huck (Prior) on Mar 23, 2017 at 13:13 UTC |