Perl: How to direct a key / value pair to hashref and save the link

$a = {b=>{c=>1}}; # set up ref $b = $a->{b}; # ref the ref $b .= (d=>1,e=>1); # where we want to assign multiple key/val at once 

At the end of this, $a should look like this:

  •  { 'b' => { 'c' => 1, 'd' => 1, 'e' => 1 } }; 

At the end of this, $b should look like this:

  •  { 'c' => 1, 'd' => 1, 'e' => 1 } 

Note: this will be the same as doing:

 $b->{d} = 1; $b->{e} = 1; 

$b = { %$b, d=>1, e=>1 }; Undesirable because it creates a copy of $a and loses the link.

+6
source share
2 answers
 %{$b} = ( d => 1, e => 1 ); 

You simply remove the reference to the anonymous hash-ref so that it looks like a hash for the assignment operator.

You can even do this:

 %{$b} = ( %{$b}, d => 1, e => 1 ); 

In these cases, %{$b} is just a visual convenience (although in some cases it may be syntactic ambiguity) for %$b .

... or you could do ...

 foreach ( qw/ de / ) { $b->{$_} = 1; } 

Obviously, you probably do not intend to assign the value "1" to everyone. So what about the fragment:

 @{$b}{ qw/ de / } = ( 1, 1 ); 

Slices are discussed in perldoc perldata , but a not-so-good description of perldoc for taking a fragment of an anonymous hash. To do this, you need to come to terms with all the Perl documentation on the links, and then extrapolate how to apply this to the slice syntax .... or check the anonymous hash fragments on PerlMonks.

+8
source

Use hash slice notation.

  @$b{"d","e"} = (1,1); %newdata = (d => 1, e => 1); @$b{keys %newdata} = values %newdata; 
+7
source

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


All Articles