{ 'b' => {...">

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?

+6
source share
3 answers

Something like that:

 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; 
+7
source

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.)

+4
source
 use strictures; use Data::Diver qw(DiveVal); my ($hash, $path, $value) = ( { 'a' => { 'b' => { 'c' => 'value' } } }, 'abc', 'something', ); DiveVal($hash, split /[.]/, $path) = $value; # { a => { b => { c => 'something' } } } 
+3
source

Source: https://habr.com/ru/post/917702/


All Articles