【问题标题】:Update value in hash of hashes in perl在 perl 中更新哈希值
【发布时间】:2018-05-18 10:13:16
【问题描述】:

我是 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 };。

我做错了什么?

【问题讨论】:

  • 您应该将标记为# I can't change this 的行更改为my $self = shift; 和my ($text) = @_; 这是很常见的做法,并将显式参数留给@_ 中的子例程,但删除对象或类接收应该是只读的消息。

标签: perl hash


【解决方案1】:

好吧,您的错误是因为您的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 通常用于引用 对象,如果将其用于“普通”哈希,可能会让人感到困惑。

【讨论】:

    猜你喜欢
    • 2014-04-13
    • 2015-01-26
    • 2010-10-20
    • 2021-06-01
    • 2019-05-19
    • 2015-09-15
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    相关资源
    最近更新 更多