my final code: #!/usr/bin/perl use strict; use warnings; use diagnostics; # Open file1 to read open my $input_file1, '<', "rmsd1.xvg" or die qq{Failed to open "rmsd1.xvg" for writing: $!}; # Open file2 to read open my $input_file2, '<', "rmsd2.xvg" or die qq{Failed to open "rmsd2.xvg" for writing: $!}; # Open new file to write open my $out_file, '>', "rmsd.xvg" or die qq{Failed to open "rmsd.xvg" for writing: $!}; # Copy data from one file to another. my %file2data; while(<$input_file2>) { next if /(^\s*$)|(^#)|(^@)/; my @columns2 = split; $file2data{$columns2[0]} = $columns2[1]; } while(<$input_file1>) { next if /(^\s*$)|(^#)|(^@)/; my @columns1 = split; print $out_file join("\t", $columns1[0],$columns1[1], $file2data{$columns1[0]}), "\n"; } close($input_file2); close($input_file1); close($out_file);