use Data::Dumper; # Trying to guarantee this: #$self->{db}->{offer}->{product_id}->{name} # We start with a fully formed hashref $self->{db}->{offer}->{product_id}->{name} = 1; # and undef somewhere in the middle undef $self->{db}; # Show the structure just to prove it is too short print Dumper $self; my $Last = $self; for (['db',{}], ['offer',{}], ['product_id',&func], ['name',42]){ defined $Last->{$_->[0]} or $Last->{$_->[0]} = $_->[1]; $Last = $Last->{$_->[0]}; } print Dumper $self; # func() is the default for key 'product_id' above sub func{ {} } #### $VAR1 = { 'db' => undef }; $VAR1 = { 'db' => { 'offer' => { 'product_id' => { 'name' => 42 } } } };