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

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;

sub dive_val :lvalue {
   my $p = \shift;
   $p = \( ($$p)->{$_} ) for @_;
   return $$p;
}

my $data;
my $key = 'a.b.c';
my $val = 'value';

dive_val($data, split /\./, $key) = $val;

A more powerful (and thus slightly harder to use) version of this function is provided by Data::Diver.

use Data::Diver qw( DiveVal );

my $data;
my $key = 'a.b.c';
my $val = 'value';

DiveVal($data //= {}, map \$_, split /\./, $key) = $val;

(daxim's usage is slightly off.)


use strictures;
use Data::Diver qw(DiveVal);

my ($hash, $path, $value) = (
    { 'a' => { 'b' => { 'c' => 'value' } } },
    'a.b.c',
    'something',
);

DiveVal($hash, split /[.]/, $path) = $value;
# { a => { b => { c => 'something' } } }