use strict; use warnings; my $folder_IN = $ARGV[0]; my $finaltreefile = "./final.CSV"; my $level = 0; my $rootfile = `ls $folder_IN/$level*.CSV`; chomp($rootfile); print "rootfile: $rootfile\n"; open( my $final, '>', $finaltreefile ) or die "$finaltreefile: $!"; treebuilder($rootfile, $level+1); close($final); exit(0); sub treebuilder { my $filename = shift; my $level = shift; my $nextlevel = $level + 1; print "File level $level : $filename\n"; my $PRESENTLEVELFILE; unless(open($PRESENTLEVELFILE, '<', $filename)) { warn "$filename: $!"; return; } my $leafline = <$PRESENTLEVELFILE>; if ( $filename eq $rootfile ) { print $final "0 $leafline"; } while ( my $leafline = <$PRESENTLEVELFILE> ) { print "Leggo $leafline\n"; chomp($leafline); print "next level=$nextlevel\n"; my @element = split( '§', $leafline ); print "Find $element[0]\n"; my $NEXTLEVELFILE = $folder_IN . "/" . $level . "_" . $element[0] . ".CSV"; print "Check if file exists: $NEXTLEVELFILE\n"; print $final "$level $leafline\n"; treebuilder($NEXTLEVELFILE, $nextlevel); } close($PRESENTLEVELFILE); } #### 0 440Z0220-932§other information 1 623Z5400-1§other information 1 623Z5400-1§other information 1 623Z5400-18other information 1 623Z5400-18§other information 1 623Z5400-3§other information 1 623Z5420-1301§other information 1 623Z5420-1307§other information 1 7010902H01§other information 1 7010900H01§other information 1 623Z5466-1013§other information 1 623Z5466-1015§other information 1 623Z5465-1039§other information 1 623Z5465-1041§other information 1 623Z5465-1001§other information 2 623Z5465-1§other information 2 623Z5465-11§other information 2 CA623Z5465-1001§other information 1 623Z5420-3301§other information 1 623Z5465-41§other information 1 623Z5462-1001§other information 1 623Z5462-1003§other information 2 623Z5468-1§Other information 2 623Z5468-9§Other information 2 623Z5468-7§Other information 2 623Z5468-5§Other information 2 CA623Z5462-1003§Other information 2 BACD40AC36B30§Other information 2 623Z5469-7§Other information 2 623Z5462-3§Other information 1 7010902H01§other information 1 623Z5420-3307§other information 1 B3-15838§other information 1 623Z5422-3307§other information #### sub treebuilder { my ($filename, $level) = @_; my $PRESENTLEVELFILE; unless(open($PRESENTLEVELFILE, '<', $filename)) { warn "$filename: $!"; return; } my $leafline = <$PRESENTLEVELFILE>; print $final "0 $leafline" if ( $filename eq $rootfile ); while ( my $leafline = <$PRESENTLEVELFILE> ) { print $final "$level $leafline"; my @element = split( '§', $leafline ); treebuilder("$folder_IN/${level}_$element[0].CSV",$level + 1); } close($PRESENTLEVELFILE); }