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:
That should be fast enough for almost all purposes (about#!/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);
Benchmark for the interested:
output:#!/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) @ 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)
In reply to Re^4: Building Multi-Level Hash dynamically
by Joost
in thread Building Multi-Level Hash dynamically
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |