ryan has asked for the wisdom of the Perl Monks concerning the following question:
I'm tinkering with my personal website and have a CGI which reads in a real system directory structure to represent categories etc. The resulting hash represents the directory structure plus stores a small amount of info for particular files.
The structure looks like this as a cut-down example, it could be nested to any level, not just what is shown:
$VAR1 = { 'misc' => {}, 'docs' => { 'howtos' => { 'email' => { 'index.html' => { 'date' => '21-1-2004', 'size' => '691' } }, 'ftp' => {}, 'ssh' => {} } } };
What I want to do is directly reference one of the nested hashes based on a single string containing the real system path. If I had the string: "/docs/howtos/email/" I'd want to produce the contents of: $VAR1->{docs}->{howtos}->{email}
I came up with a seemingly dodgy way with eval as follows (this is the first time I've used eval before BTW):
# yes, I realise there is NO error checking :) # assume $tree contains data structure shown above # assume input = "/docs/howtos/email/" my $string = join('}->{',split(/\//,$input)); $string =~ s/^.(.+)/$1}/; $string = '$tree'.$string."->{'index.html'}->{size};"; # string now contains: "$tree->{docs}->{howtos}->{email}->{'index.html +'}->{size};" # constructed reference print eval $string; # explicit reference print $tree->{docs}->{howtos}->{email}->{'index.html'}->{size};
This outputs the same for both cases and does what I want - but it seems like a hack. I was curious as to how others would do it, and most probably how I *should* do it? :)
Thanks,
Ryan
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Building dynamic nested hash references
by broquaint (Abbot) on Jan 21, 2004 at 11:15 UTC | |
Re: Building dynamic nested hash references
by ysth (Canon) on Jan 21, 2004 at 11:14 UTC | |
Re: Building dynamic nested hash references
by BrowserUk (Patriarch) on Jan 21, 2004 at 12:08 UTC | |
Re: Building dynamic nested hash references with map
by l3nz (Friar) on Jan 21, 2004 at 12:15 UTC | |
Re: Building dynamic nested hash references
by ryan (Pilgrim) on Jan 21, 2004 at 12:05 UTC | |
by Roy Johnson (Monsignor) on Jan 21, 2004 at 15:49 UTC |
Back to
Seekers of Perl Wisdom