put_element( $DATA{3}, 'h', 'i', 'worked' ); #### put_element( \%DATA, 3, 'h', 'i', 'worked' ); #### put_element( \%DATA, qw(3 h i worked) ); #### 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; }