my @files = qw(File1.txt File2.txt); my %tree; my(@iterations, @names); # order foreach my $file (qw(File1.txt File2.txt)) { open my $fh, '<', $file or die "Cannot open file $file: $!"; (my $name = $file) =~ s/\.\w+$//; # remove extension push @refs, $ref; # order my($iteration); while(<$fh>) { chomp; if(/^Iteration /) { $iteration = $_; push @iterations, $iteration unless $tree{$iteration}; # key order } elsif(my($i) = /^(\d+):/) { $tree{$iteration}[$i]{$name} = $_; } } } #### use Data::Dumper; print Dumper \%tree; #### foreach my $iteration (@iterations) { print "$iteration\n"; # section header my $section = $tree{$iteration}; # array ref for my $i (0 .. $#$section) { my @data; foreach my $name (@names) { my $data = $section->[$i]{$name}; next unless defined $data; push @data, "$name:$data"; } if(@data) { my $line = join " ", @data; print "$line\n"; } } }