更新 perl 中哈希值的哈希值



我是Perl的初学者。我有一个哈希$self其中包含其他哈希,特别是它包含一个带有密钥params的哈希。我想将对应于params的关键color的值从black更新为white。 换句话说,$self如何:

{
'params' => {
'color' => 'black',
#other keys/values here...
},
#other hashes here...
};

我想要什么:

{
'params' => {
'color' => 'white',
#other keys/values here...
},
#other hashes here...
};

我尝试过:

sub updatePrice {
my ($self, $text) = @_; # I can't change this
my %params = %{$self->{params}};
$params{color} = 'white'; 
print Data::Dumper::Dumper{$params{color}};
# ...
}

但是我收到Odd number of elements in anonymous hash警告,而打印$VAR1 = { 'white' => undef };.

我做错了什么?

好吧,你的错误是因为你的Data::Dumper行中有太多{

{}也是一个匿名哈希构造函数,因此您可以:

my $hashref = { 'key' => 'value' };

这就是你在将其传递给之前正在做的事情Data::Dumper只是你只提供一个值 - 这就是为什么你得到"奇数个元素"警告的原因。(无论如何,{ 'white' }的哈希不是您要实现的)

尝试:

print Data::Dumper::Dumper  $params{color};

或者只是:

print Data::Dumper::Dumper %params;

而且 - 你可能以错误的方式这样做 -%params$self树的副本,所以更新它不会改变原始的。

my %params = %{$self->{params}};

创建副本。

您可能希望:

$self -> {params} -> {color} = "white"; 
print Dumper $self; 

可能值得注意的是 -$self通常用于引用对象,如果您将其用于"普通"哈希,可能会感到困惑。

最新更新