Amoe has asked for the wisdom of the Perl Monks concerning the following question:
Rightyright. I have a hash reference which contains an unknown amount of hash references as values, which themselves contain hash references...and so on ad finitum, you know the drill. We'll call it $structure. That's all very easy to access when I know what I'm looking for. But, say I get a series of keys from a user, and have them in an array. The array looks like this:
('stuff', 'hierarchy', 'album')Here, stuff is the first-level key of the structure, hierarchy is the hash reference returned by $structure->{stuff}, et cetera, et cetera. To write it in Perl, this chain would look like this:
$structure->{stuff}{hierarchy}{album}I figured out a way to descend the structure when I only have to locate a value from it based on that list:
my $target = 'bar'; # the end key my $path = ('stuff', 'hierarchy', 'album'); my $nodule = $structure; while (my $next_key = shift @path) { $nodule = $nodule->{$next_key}; } my $triumphant = $nodule->{$target};
That made me feel pretty good. But then the jig was up: I had to change a value in the structure. Essentially, I had to change $nodule->{$target}. I can't just convert that - it needs to be reflected as a change in the whole $structure, and I'm wiping out the rest of the structure as I go along. The only way I can think of doing this at the moment is by constructing an elaborate eval STRING statement by concatenating the list into Perl syntax and running that. But that introduces a whole range of new concerns, and I don't really want to do that. There must be another way.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: descending a tree of hash references
by Chmrr (Vicar) on Feb 19, 2002 at 22:01 UTC | |
Re: descending a tree of hash references
by YuckFoo (Abbot) on Feb 19, 2002 at 22:11 UTC | |
by Amoe (Friar) on Feb 20, 2002 at 12:35 UTC | |
by YuckFoo (Abbot) on Feb 20, 2002 at 20:10 UTC | |
Re: descending a tree of hash references
by trs80 (Priest) on Feb 19, 2002 at 23:23 UTC | |
by merlyn (Sage) on Feb 19, 2002 at 23:31 UTC | |
by tachyon (Chancellor) on Feb 20, 2002 at 00:02 UTC |