Search code examples
perlperl-data-structures

Convert string "a.b.c" to $hash->{a}->{b}->{c} in Perl


I've dynamic nested hash-refs like this:

my $hash = { 'a' => { 'b' => { 'c' => 'value' } } };

I want to set the value of c to 'something' by allowing the user to input "a.b.c something".

Now getting the value could be done like this:

my $keys = 'a.b.c'; 
my $v='something';
my $h = $hash;
foreach my $k(split /\./, $keys) {
  $h = $h->{$k};
}
print $h; # "value"

But how would I set the value of key c to $v so that

print Dumper $hash;

would reflect the change? $h is not a ref at the end of the foreach loop, so changing that won't reflect the change in $hash. Any hints how to solve the knots in my head?


Solution

  • Something like this:

    my $h = $hash;
    my @split_key = split /\./, $keys;
    my $last_key = pop @split_key;
    foreach my $k (@split_key) {
        $h = $h->{$k};
    }
    $h->{$last_key} = $v;