while () { ## (note: using logical indenting) if ($found) { if (/^$number/) { if (/^-/) { print COPYFILE "$_\n"; $found = 0; ## <<== this is why } } } elsif ... } #### $found = 0; while () { if ( $found ) { if ( /^\d+/ ) { # does line start with a digit? $found = 0; # then we're done printing stuff } elsif ( /^-/ ) { # otherwise, if there's stuff print COPYFILE; # then we print it } } elsif ( /^$name/ ) { $found = 1; } }