http://qs321.pair.com?node_id=322837

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