my %h; # build a giant hash of all the info. Keys are ids, values # are hashrefs whose keys are the source filename and whose # values are the lines themselves. while (<>) { my @fields = split ','; $h{$fields[0]}{$ARGV} = $_; } # for each id (lexically sorted) for my $id (sort keys %h) { my @keys = keys %{$h{$id}}; # if it was present in only one file, print it and move on if (scalar @keys == 1) { print $h{$id}{$keys[0]}; next; } # if it was present in more than one, find out whether # all the lines are the same by building a hash with # each line as the key, then testing whether you end # up with more than one key. my %cmp; $cmp{$_} = '' for values %{$h{$id}}; print keys %cmp if scalar keys %cmp == 1; }