[ACCEPTED]-How can I replace a Perl hash key?-replace

Accepted answer
Score: 53

The delete operator returns the value being deleted. So 1 this

$data->{key3}{key4}{key6} = delete $data->{key3}{key4}{key5}

will do what you're looking for.

Score: 9

You can't replace it, but you can make a 12 new key easily, and then delete() the old one:

$data->{key3}{key4}{key6} = $data->{key3}{key4}{key5};
delete $data->{key3}{key4}{key5};

Of 11 course, you could make a fairly simple subroutine 10 to do this. However, my first approach was 9 wrong, and you would need to make a more 8 complex approach that passes in the data 7 structure to modify and the element to be 6 modified, and given that you want elements 5 several levels deep this may be difficult. Though 4 if you don't mind a little clutter:

sub hash_replace (\%$$) {
  $_[0]->{$_[2]} = delete $_[0]->{$_[1]}; # thanks mobrule!
}

Then 3 call it:

hash_replace %{$data->{key3}{key4}}, "key5", "key6";

Or the cool way (How better to say 2 that we're transforming "key5" into 1 "key6" ?):

hash_replace %{$data->{key3}{key4}}, key5 => "key6";

(Tested and works)

Score: 0

This 'works', but it is very hard-coded.

#!/bin/perl -w
use strict;

my $data = {
    'key1' => {
        'key2' => 'value1'
    },
    'key3' => {
        'key4' => {
            'key5' => 'value2'
        }
    },
};

print "$data->{key3}->{key4}->{key5}\n";

my $save = $data->{key3}->{key4}->{key5};
delete $data->{key3}->{key4}->{key5};
$data->{key3}->{key4}->{key6} = $save;

print "$data->{key3}->{key4}->{key6}\n";

You 3 can eliminate the '->' operators between 2 the hash subscripts, but not the one after 1 '$data' - as in Chris Lutz's solution.

More Related questions