use Modern::Perl; my %first_file; { open my $FIRST, '<', 'first.txt' or die $!; while (<$FIRST>) { chomp; $first_file{$_} = '' ; } } my (@both, @first, @second); { open my $SECOND, '<', 'second.txt' or die $!; while (<$SECOND>) { chomp; if (exists $first_file{$_}) { push @both, $_; delete $first_file{$_}; } else { push @second, $_; } } } @first = keys %first_file;