in reply to Re^3: Building Multi-Level Hash dynamically
in thread Building Multi-Level Hash dynamically

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.