I'm parsing a large file in Perl line-by-line (terminated by \n), but when I reach a certain keyword, say "TARGET", I need to grab all the lines between TARGET and the next completely empty line.
So, given a segment of a file:
Line 1
Line 2
Line 3
Line 4 Target
Line 5 Grab this line
Line 6 Grab this line
\n
It should become:
Line 4 Target
Line 5 Grab this line
Line 6 Grab this line
The reason I'm having trouble is I'm already going through the file line-by-line; how do I change what I delimit by midway through the parsing process?
You want something like this:
Edit to fix the exit condition as per the note below.
The short answer: line delimiter in perl is
$/
, so when you hit TARGET, you can set$/
to"\n\n"
, read the next "line", then set it back to "\n"... et voilà!Now for the longer one: if you use the
English
module (which gives sensible names to all of Perl's magic variable, then$/
is called$RS
or$INPUT_RECORD_SEPARATOR
. If you useIO::Handle
, thenIO::Handle->input_record_separator( "\n\n")
will work.And if you're doing this as part of a bigger piece of code, don't forget to either localize (using
local $/;
in the appropriate scope) or to set back$/
to its original value of"\n"
.The range operator is ideal for this sort of task: