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


In reply to Building dynamic nested hash references by ryan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.