my $cnt=0; while (my $line = <>) { $cnt++ if $line =~ /formulae/; last if $cnt>1; } if ($cnt>1) { # got what we wanted } else { # word didn't appear twice }