http://www.perlmonks.org?node_id=1091649


in reply to Parse data representing hash

Here is my humble attempt to solve your interesting puzzle:

use strict; use warnings; use Data::Dumper; my %hash; my @row; while(<DATA>){ my ($level, $word) = /^(\s*)(\w*)$/; $level = length($level)/4; $row[$level] = $word; $#row = $level; my $last = \%hash; for (0..$#row) { $last->{$row[$_]} = $_ == $#row ? undef : {} if not defined $last- +>{$row[$_]}; $last = $last->{$row[$_]}; } } print Dumper \%hash; __DATA__ one two three four five six

Replies are listed 'Best First'.
Re^2: Parse data representing hash
by peterp (Sexton) on Jun 29, 2014 at 18:47 UTC

    Thank you very much for providing your attempt, its very similar to my alternative version to using Data::Diver, but has provided some insight into ways I can improve. Notably, the $#array = $index syntax is new to me and is a nice alternative to using splice or a slice. Also, I prefer your for loop over my recursive function to construct the resultant hash.

    Regards.