sub put_element { my ($hashref, @path) = @_; # The leaf node and its value are special my $value = pop @path; my $leaf = pop @path; # walk the tree, create non-existing nodes for my $node (@path) { $hashref = $hashref->{$node} ||= {}; } # Finally, set the value at the leaf $hashref->{$leaf} = $value; }