in reply to transform array into a data structure

Here is a recursive solution written more for clarity than conciseness. It'll give a basic idea anyway:
#!/user/bin/env perl use strict; use warnings; use Data::Dumper; my @array = qw(a b c d e f g h i 123); my $recurse_level = 0; sub to_hash { my $hash_ref = shift; my @array = @_; my $array_count = @array; die "Need at least 2 elements in original array" if (0 == $recurse_l +evel && 2 > $array_count); my $index; if (2 < $array_count) { $index = shift @array; $recurse_level++; $hash_ref->{$index} = to_hash({},@array); } else { $index = shift @array; $hash_ref->{$index} = shift @array; } return $hash_ref; } my $hash_ref = to_hash({},@array); print Dumper($hash_ref);
Output:
$VAR1 = { 'a' => { 'b' => { 'c' => { 'd' => { 'e' => { 'f' => { 'g' => + { + 'h' => { + 'i' => '123' + } + } } } } } } } };
Update

Triple bonus points to whomever modifies this code to allow for more complex data structures to be created by feeding it multiple arrays - the current code only returns a hash for /the/ array passed to it. I know why, but I can figure out right now how to fix it...if I figure it out, I'll update the code.

Replies are listed 'Best First'.
Re^2: transform array into a data structure
by calin (Deacon) on Sep 29, 2007 at 19:29 UTC

    Do I get a simple bonus if I turn your code into a one liner :)

    my $h = pop @array; $h = {$_ => $h} for reverse @array;