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;
Above code demonstrated some sort what I want (but not entirely correct), however I have to make it one level up from the last "part".
I know that I cannot directly get that reference via eval. like :
$ref = eval '$base$return_from_sub'; $ref = [/whatever/];
This just make $ref pointed to something else so this won't work. But I wonder is there any trick can do something like :
$ref = eval '\$refString'; deference( $ref ) = $whatever ;# [] {} ""
Provided that, I don't know what will be returned from the sub, and I don't know what's gonna be stored. both (return_from_sub and to write) can be array ref, hash ref, code ref, whatever ref or simple scalar.
In reply to How to get a reference from an eval() string? by exilepanda
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |