turbolofi has asked for the wisdom of the Perl Monks concerning the following question:

Hi fellow monks I am struggling with a small problem - I want to print the text following a match from a regular expression, until a match of a different regular expression.
The input is this:
CR *FDA, 1997, GUID IND EXT REL OR BADAWY SIF, 1996, INT J PHARM, V128, P45 (more lines w. similar formatting) NR 42
Text with similar formatting is repeated many times in the input - I'd like to print everything between "CR " and "NR" - in all occurences in the file. The code I have thus far is this:
use strict; use warnings; my @infile = (<>); my ($citedreferences, $line); my $n = 0; foreach $line (@infile){ if ($line =~ m{^CR .+}gsi){ do{ $n++; print $n . $line; next; } until ($line =~ m{^NR}gsi) } };

However, this only prints the lines matching the first regular expression. Any tips to point me in the right direction would be much appreaciated

Replies are listed 'Best First'.
Re: Printing lines after regexp match until match of a different regexp
by JavaFan (Canon) on Jun 14, 2009 at 16:31 UTC
    Use the flipflop operator:
    while (<DATA>) { print if /CR/ .. /NR/; } __DATA__ foo bar foo CR *FDA, 1997, GUID IND EXT REL OR BADAWY SIF, 1996, INT J PHARM, V128, P45 (more lines w. similar formatting) NR 42 more text CR yada yada yada yada yada NR 17 rubbish
    Output:
    CR *FDA, 1997, GUID IND EXT REL OR BADAWY SIF, 1996, INT J PHARM, V128, P45 (more lines w. similar formatting) NR 42 CR yada yada yada yada yada NR 17
      Haha, so simple. Fantastic. Thanks a bunch!