Convert string "abc" to $ hash & # 8594; {a} & # 8594; {b} & # 8594; {c} in Perl
I have dynamic nested hash links:
my $hash = { 'a' => { 'b' => { 'c' => 'value' } } };
I want to set the value of c to "something", allowing the user to enter "abc something".
Now, getting the value can be done as follows:
my $keys = 'abc'; my $v='something'; my $h = $hash; foreach my $k(split /\./, $keys) { $h = $h->{$k}; } print $h; # "value"
But how would you set the value of key c
to $v
so that
print Dumper $hash;
will reflect the change? $h
not ref at the end of the foreach loop, so changing this parameter will not affect changing $hash
. Any tips on how to solve the nodes in my head?
The output of the last key for wusses !;)
sub dive :lvalue { my $r = \shift; $r = \( ($$r)->{$_} ) for @_; return $$r; } my $data; my $key = 'abc'; my $val = 'value'; dive($data, split /\./, $key) = $val;
A more powerful (and therefore slightly difficult to use) version of this function is provided by Data :: Diver .
use Data::Diver qw( DiveVal ); my $data; my $key = 'abc'; my $val = 'value'; DiveVal($data //= {}, map \$_, split /\./, $key) = $val;
(Using daxim is slightly disabled.)