foreach my $line (@lines) { my @chr_fields = grep {$_ =~ m/^chr/} split ("\t", $line) if ( # If... @chr_fields == 2 # ...there are exactly two chr* fields... && $chr_fields[0] ne $chr_fields[1] # ...which are not exactly the same... ) { print $w $line; } } close $w;