I am looking for a more effective way to write this affect
subroutine in perl:
#!/usr/bin/perl
use 5.010;
use strict;
my @keys = qw/foo bar baz/;
my %hash = ( foo => {babel => 'fish'} );
affect (\%hash, 42);
sub affect {
my $ref = shift;
$ref = $ref->{$keys[$_]} //= {} for (0.. $#keys - 1);
$ref->{$keys[$#keys]} = shift;
}
use Data::Dumper;
print Dumper \%hash;
And the expected result:
$VAR1 = {
'foo' => {
'bar' => {
'baz' => 42
},
'babel' => 'fish'
}
};
I was thinking about things like this, but obviously it can't work like this:
%hash{ @keys } = 42;
Any idea?
it would be more effective if you actually passed the keys to it! Let's make it an lvalue sub at the same time.
There are two added advantages to this implementation.
First, you can use it to peek into the data structure.
Second, it will autovivify its first argument.
This function already exists as Data::Diver's
DiveVal
.Comparison of the flow of
affect
anddive_val
:affect
$ref
is a reference to a hash.dive_val
$p
is a reference to a scalar.dive_val
's approach is purer.affect
which creates it in the previous loop pass).dive_val
could easily be extended to support mixed array/hash structures.