简体   繁体   中英

Update value in hash of hashes in perl

I'm a very beginner in Perl. I have an hash $self which contains other hashes, in particular it contains an hash with the key params . I want to update the value correspondent to the key color of params , from black to white . In other words, how $self is:

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

What I want:

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

What I tried:

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

But I get a Odd number of elements in anonymous hash warning, while the printing is $VAR1 = { 'white' => undef }; .

What am I doing wrong?

Well, your error is caused because you've got too many { in your Data::Dumper line.

{} is also an anonymous hash constructor, so you can:

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

That's sort of what you're doing before passing it to Data::Dumper only you're only supplying one value - which is why you get the "odd number of elements" warning. (And a hash of { 'white' } isn't what you're trying to achieve anyway)

Try:

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

Or just:

print Data::Dumper::Dumper \%params;

But also - you're probably doing this the wrong way - %params is a copy of the tree from $self , so updating it doesn't change the original.

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

creates a copy.

You probably want:

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

It's probably worth noting - $self is typically used to reference an object , and it may get confusing if you use it for a "normal" hash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM