in reply to dynamic hash nesting
Is this something that is possible in Perl?
Of course.
The usual strategy to build a data structure of arbitary depth is the "create as you traverse" approach, ie you just walk level by level, create them if needed, and always keep a reference to the previous level to start the current iteration from.
Here you don't even need to do that, because you create at most one level at a time.
Since you didn't explain exactly how the resulting data structure should look like, I've added the description as an extra key called DESCRIPTION.
Without further ado, the code:
use 5.010; use strict; use warnings; my %h; my @depth; while (<DATA>){ chomp; /^(\s*)/; # 'cause it's 4 spaces here, not tabs my $level = length($1) / 4; s/^\s+//; my ($key, $val) = split /\s{2,}/, $_, 2; my $h = $level == 0 ? \%h : $depth[$level - 1]; $h->{$key}{DESCRIPTION} = $val; $depth[$level] = $h->{$key}; } use Data::Dumper; print Dumper \%h; __DATA__ Assault Assault Battery Assault and Battery Sexual Sexual Assault Deadly Assault with a deadly weapon with Assault with a deadly weapon without Assault without a deadly weapon Aggravated Aggravated Assault
Here is the output, with reduced indentation for better readability:
VAR1 = { 'Assault' => { 'Sexual' => { 'DESCRIPTION' => 'Sexual Assault' }, 'Battery' => { 'DESCRIPTION' => 'Assault and Battery' }, 'DESCRIPTION' => 'Assault', 'Aggravated' => { 'DESCRIPTION' => 'Aggravated Assault' }, 'Deadly' => { 'DESCRIPTION' => 'Assault with a deadly weapon', 'without' => { 'DESCRIPTION' => 'Assault without a deadly weapon' }, 'with' => { 'DESCRIPTION' => 'Assault with a deadly weapon' } } } };
To look up elements of arbitrary depth, you can use something like
sub lookup { my $h = \%h; $h = $h->{$_} for @_; return $h->{DESCRIPTION}; } say lookup 'Assault'; say lookup qw/Assault Deadly with/;
Which again drags a reference from the lookup of the previous level to achieve arbitrary depth.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: dynamic hash nesting
by karrakis (Novice) on Aug 16, 2012 at 21:35 UTC | |
by locked_user sundialsvc4 (Abbot) on Aug 17, 2012 at 02:37 UTC |