#!/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); #### #!/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 }, } ); #### Benchmark: timing 100000 iterations of eval_string, manual... eval_string: 10 wallclock secs ( 9.31 usr + 0.05 sys = 9.36 CPU) @ 10683.76/s (n=100000) manual: 2 wallclock secs ( 2.07 usr + 0.01 sys = 2.08 CPU) @ 48076.92/s (n=100000)