Oops, forgot one:
What would be your method of choice to solve OP's problem?
If I wanted a silly structure like that, I'd probably do it like this:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @arr = qw(aa bb cc dd ee ff); sub build { my %hash; my $ref = \%hash; while (defined (my $element = shift @_)) { $ref = ($ref->{$element} = @_ ? {} : 0); } \%hash; } print Dumper build(@arr);
That should be fast enough for almost all purposes (about 10 5 times faster than the eval string method), and it has none of the security problems.

Benchmark for the interested:

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use Benchmark 'timethese'; timethese( 100000, { 'manual' => sub { my @arr = qw(aa bb cc dd ee ff); my %hash; my $ref = \%hash; while (defined (my $element = shift @arr)) { $ref = ($ref->{$element} = @arr ? {} : 0); } \%hash; }, 'eval_string' => sub { my $hoh; my @array = qw(aa bb cc dd ee ff); my %hash; my $eval_string = '$hoh->{' . (join '}{', @array) . '} = 0'; eval "$eval_string"; $hoh }, } );
output:
Benchmark: timing 100000 iterations of eval_string, manual... eval_string: 10 wallclock secs ( 9.31 usr + 0.05 sys = 9.36 CPU) @ 1 +0683.76/s (n=100000) manual: 2 wallclock secs ( 2.07 usr + 0.01 sys = 2.08 CPU) @ 48 +076.92/s (n=100000)
Updated benchmark, fixed bug.

In reply to Re^4: Building Multi-Level Hash dynamically by Joost
in thread Building Multi-Level Hash dynamically by Anonymous Monk

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.