UPDATE/WARNING: I was curious how difficult an eval
solution might be, but as
merlyn points out, this code is
dangerous and slower then other safer solutions.
Despite
merlyn's staunch reply about
not using it, it is still a soltuion and we all know TIMTOWTDI.
The original
poster made it clear that he understood eval was a bad idea.
I learned my lesson, I will not post code just to post code,
bad trs80, bad.
I know you requested a non eval solution, but I couldn't
restrain myself.
use strict;
use warnings;
my $structure = {
stuff => {
hierarchy => {
album => {
bar => 'the right one',
},
},
},
};
my $path = [ 'stuff', 'hierarchy', 'album' , 'bar' ];
print get_structure_value($structure,$path) , "\n";
$structure = return_new_structure($structure,$path,'new value');
print get_structure_value($structure,$path) , "\n";
sub make_eval {
my ($path) = shift;
my $string = "\$hashref->";
$string .= "{$_}" for @$path;
return $string;
}
sub get_structure_value {
my ($hashref,$path) = @_;
my $string = &make_eval($path);
return eval($string);
}
sub return_new_structure {
my ($hashref,$path,$set) = @_;
my $string = &make_eval($path);
eval("$string = '$set'");
return $hashref;
}
Excuse the verbose sub names, I wanted it to be clear what
each did, I created a sigle sub to being with but I didn't
like the interface, I think this makes it clear what you
are getting back.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.