我可以从列表中初始化哈希,例如:
my %hash = (1..10);
my %hash2 = split /[\n=]/;
是否有更好的(更简洁的)方法将新的键/值列表添加到哈希而不是使用临时变量?
while (<>) {
my ($k, $v) = split /=/, $_, 2;
$hash{$k} = $v;
}
答案 0 :(得分:0)
也许我错了,但下一个
use 5.014;
use warnings;
use Data::Dumper;
#create a hash
my %hash = map { "oldvar" . $_ => "oldval" . $_ } (1..3);
#add to the hash
%hash = (%hash, map {split /[=\n]/} <DATA>);
say Dumper \%hash;
__DATA__
var1=val1
var2=val2
var3=val3
打印
$VAR1 = {
'oldvar1' => 'oldval1',
'oldvar2' => 'oldval2',
'var1' => 'val1',
'var3' => 'val3',
'oldvar3' => 'oldval3',
'var2' => 'val2'
};