我可以从列表中初始化哈希,例如:
my %hash = (1..10);
my %hash2 = split /[\n=]/;
有没有比使用临时变量更好(更简单)的方法来将新键/值列表添加到哈希中?
while (<>) {
my ($k, $v) = split /=/, $_, 2;
$hash{$k} = $v;
}
有可能,是的。这就像在现有总数中添加一些数字 - 您可以这样完成:
my $total = 1 + 2 + 3; # here's the existing total
# let's add some additional numbers
$total = $total + 4 + 5; # the $total variable appears both
# left and right of the equals sign
将值插入现有哈希时,您可以执行类似操作...
my %hash = (a => 1, b => 2); # here's the existing hash.
# let's add some additional values
$_ = "c=3" . "\n" . "d=4";
%hash = (%hash, split /[\n=]/); # the %hash variable appears both
# left and right of the equals sign
此外,还有一个很好的捷径:
$total += 4 + 5;
将值插入散列时,没有这样的捷径。
也许我错了,但下一个
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'
};