in reply to How do I Extract contents from given input files and merge into one text file based on Unique keys present in input files

Similar to the idea given by bart and dwm042 above but a slightly different implementation using a hash of hashes with multiple values per key.

#!/usr/bin/perl -w use strict; my @list_of_files = qw(file1.txt file2.txt); my %data; my $file_num = 0; foreach my $file_name(@list_of_files){ $file_num++; my $file = 'File'.$file_num; my $iter; my $flag = 0; open FH, $file_name or die "Cannot open $file_name. $!"; while(<FH>){ chomp; if($_ =~ /(Iteration.+)/){ $iter = $1; $flag = 1; next; } if(/^$/){ $flag = 0; } if($flag){ push( @{$data{$iter}{$file}}, $_ ); } } close FH; } foreach my $iter ( sort keys %data ) { print "$iter\n"; my $size; my $index = 0; do { for my $file ( sort keys %{ $data{$iter} } ) { print "$file: ", @{$data{$iter}{$file}}[$index], " "; $size = $#{$data{$iter}{$file}}; } $index++; print "\n"; } while($index<=$size); print "\n"; }
  • Comment on Re: How do I Extract contents from given input files and merge into one text file based on Unique keys present in input files
  • Download Code