in reply to Re: Convert array to tree OR why variable changes arbitrarily
in thread Convert array to tree OR why variable changes arbitrarily
but the output is still confusing:#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @arr = ( 'ng1', ['ng1_1','ng1_2', 'ng1_3', 'ng1_4'], 'ng2', ['ng2_1','ng2_2', 'ng2_3', 'ng2_4'], 'ng3', ['ng3_1','ng3_2', 'ng3_3', 'ng3_4'], 'ng1_1', ['ng1_1_1','ng1_1_2', 'ng1_1_3', 'ng1_1_4'], 'ng1_1_1', ['ng1_1_1_u1', 'ng1_1_1_u2', 'ng1_1_1_u3'], 'ng2_1', ['ng2_1_u1', 'ng2_1_u2', 'ng2_1_u3'] ); my @tree; for (my $j=0; $j < (@arr/2); $j+=2){ $tree[$j] = $arr[$j]; $tree[$j+1] = [ @{$arr[$j+1]} ]; for (my $i=$j+2; $i < @arr; $i+=2){ buildTree(\@tree, $arr[$i], [ @{$arr[$i+1]} ]); } } print "\@arr:\n"; print Dumper @arr; print "\@tree:\n"; print Dumper @tree; sub buildTree{ my ($tree, $parNg, $subNg) = @_; for my $treeElement (@{$tree}){ if (ref $treeElement eq "ARRAY"){ &buildTree($treeElement, $parNg, $subNg); } else{ if ($treeElement eq $parNg){ my ($index) = grep { $tree->[$_] eq $treeElement } 0..scalar(@ +$tree)-1; splice @{$tree}, $index + 1, 0, $subNg; #print Dumper \@tree; } } } }
Am I still missing something? Thank you very much.$VAR1 = 'ng1'; $VAR2 = [ 'ng1_1', [ 'ng1_1_1', [ 'ng1_1_1_u1', 'ng1_1_1_u2', 'ng1_1_1_u3' ], 'ng1_1_2', 'ng1_1_3', 'ng1_1_4' ], [ 'ng1_1_1', $VAR2->[1][1], [ 'ng1_1_1_u1', 'ng1_1_1_u2', 'ng1_1_1_u3' ], 'ng1_1_2', 'ng1_1_3', 'ng1_1_4' ], [ 'ng1_1_1', $VAR2->[1][1], $VAR2->[2][2], [ 'ng1_1_1_u1', 'ng1_1_1_u2', 'ng1_1_1_u3' ], 'ng1_1_2', 'ng1_1_3', 'ng1_1_4' ], 'ng1_2', 'ng1_3', 'ng1_4' ]; $VAR3 = 'ng2'; $VAR4 = [ 'ng2_1', [ 'ng2_1_u1', 'ng2_1_u2', 'ng2_1_u3' ], [ 'ng2_1_u1', 'ng2_1_u2', 'ng2_1_u3' ], 'ng2_2', 'ng2_3', 'ng2_4' ]; $VAR5 = 'ng3'; $VAR6 = [ 'ng3_1', 'ng3_2', 'ng3_3', 'ng3_4' ];
|
|---|