my $line = 4; while (@lines > 3) { # check first 3 lines against the 4th line my @vals = split /\s+/, $lines[3]; my @chk = split /\s+/, join(' ', @lines[0..2]); my %match; foreach my $val (@vals) { $match{$val}++ if grep { $val eq $_ } @chk; } my @match = sort keys %match; my @nomatch = grep { not exists $match{$_} } @vals; my $match = @match; my $nomatch = @nomatch; # do whatever you want with the matches and no-matches print MATCH "$line: \tmatch = @match\n"; print NOMATCH "$line: \tnomatch = @nomatch\n"; $line++; # get rid of first line so next loop will be 2-6 and so on shift @lines; }