How do I populate a hash (that has been defined in

2019-07-25 13:00发布

How do I populate a hash (that has been defined in a separate file) in my Perl script and do necessary operations on it?

For ex:

file1.pl -- contains the defined hash,

file2.pl -- user defined code that should populate the hash from file1.pl

my %tgs = (
    'articles' =>  {
        'vim' => '20 awesome articles posted',
        'awk' => '9 awesome articles posted',
        'sed' => '10 awesome articles posted'
    },

    'ebooks' =>  {
        'linux 101'   => 'Practical Examples to Build a Strong Foundation in Linux',
        'nagios core' => 'Monitor Everything, Be Proactive, and Sleep Well'
    },
);

1条回答
等我变得足够好
2楼-- · 2019-07-25 13:48

@Gibron actually has already answered your question.
So I just show you the code, which you may be more interested.
The way of populating an ordinary hash is the same with that of populating a 'hash on hash'.
I'm using Data::Dumper to show the hash structure directly, you can choose your own way to know what the final hash contains.

use strict;
use Data::Dumper qw(Dumper);
do 'file1.def'; # evaluate file1

# add new sub key and value to 'hash of hash'
$file1::tgs{'articles'}{'emacs'} = '21 awesome articles posted';

# create a completely new pair
$file1::tgs{'new_key'}{'new_sub_key'} = 'new_value';

# see the result
print Dumper (\%file1::tgs);
查看更多
登录 后发表回答