http://www.perlmonks.org?node_id=1203086


in reply to Re: [Solved]Need to extract a particular block of lines between two patterns
in thread [Solved]Need to extract a particular block of lines between two patterns

Do you see the very-obvious bug in the code? Obviously you do.

Sorry, but I don't. Could you explain or demonstrate the bug with an SSCCE?

There is only one point in time when $count will be exactly equal to 2, and anyone could spot the flaw immediately.

That seems to be the OP's specification, "extract only the second block of lines that meet the pattern" (emphasis mine). Note how the OP's sample input data explicitly says "lines not to be extracted". I've added an extra block to the input for testing:

use warnings; use strict; my $count = 0; while (<DATA>) { if (/START/ .. /END/) { $count++ if /START/; print if ($count == 2); } } __DATA__ abc efg ... START lines NOT to be extracted 1 END START lines to be extracted END START lines NOT to be extracted 2 END START lines NOT to be extracted 3 END

Outputs:

START lines to be extracted END

... which seems to me to meet the specification. Cristoforo's code also works as posted, except that it does not output the START and END markers.

Whereas your code, once I fix all the syntax errors and change "do something with the line" to a print, outputs for the same sample input:

lines to be extracted lines NOT to be extracted 3

Update: Added the last two paragraphs, and minor edits for clarity.