use Data::Dumper; use strict; no warnings; no autovivification; my $return_from_sub = '{X}{Y}' ; # a result return from some sub my $to_process = '$x->' . $return_from_sub; # my local def my $x = { Y => { Z => 10, } }; # after some regex work on the $to_process my $lastPart = 'Y' ; # the last part from $to_process my $base = '$x->{X}' ; # before the $lastPart my $lastPartIs = "HASH" ; my $newData = [qw/a b c/]; my $ref = eval $base || eval "$base = {}"; # whatever it is, just make it referencable if not defined. if ( $lastPartIs eq "HASH" ) { $ref->{"$lastPart"} = $newData; # Remark 1 } elsif ( $lastPartIs eq "ARRAY" ) { $ref->["$lastPart"] = $newData; # Remark 1 } print Dumper $x;