Update: Or more compactly. Use as below.
sub x { my $aref = shift; my( $name, @kids ) = @_; push @{ $aref }, { name => $name } unless @$aref and $aref->[ -1 ]{ name } eq $name; x( $aref->[ -1 ]{ children } ||= [], @kids ) if @kids; }
#! perl -slw use strict; use Data::Dumper; sub x { my $aref = shift; my( $name, @kids ) = @_; unless( @$aref and $aref->[ -1 ]{ name } eq $name ) { push @{ $aref }, { name => $name }; } if( @kids ) { if( not exists $aref->[ -1 ]{ children } ) { $aref->[ -1 ]{ children } = []; } x( $aref->[ -1 ]{ children }, @kids ); } } my @data; chomp() and x( \@data, split ' / ', $_ ) while <DATA>; print Dumper \@data; __DATA__ one foo / bar foo / baz foo / qux / two foo / qux / three foo / qux / four five
Produces
c:\test>junk9 | more $VAR1 = [ { 'name' => 'one' }, { 'name' => 'foo', 'children' => [ { 'name' => 'bar' }, { 'name' => 'baz' }, { 'name' => 'qux', 'children' => [ { 'name' => 'two' }, { 'name' => 'three' }, { 'name' => 'four' } ] } ] }, { 'name' => 'five' } ];
In reply to Re: Convert delimited string into nested data structure
by BrowserUk
in thread Convert delimited string into nested data structure
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |