my $print_next; while (my $in = ){ foreach (@ref){ if ($print_next) { print OUT "$_"; undef $print_next; } $print_next = 1 if m/$in/; } } }