There is probably a clever way to do it with
grep and
Range Operators, but here is a way using state variables. You should change the flags to more meaningful names for your application:
use strict;
use warnings;
my $flag1 = 0;
my $flag2 = 0;
my @lines;
while (<DATA>) {
$flag2 = 1 if $flag1 and /A1/;
$flag1 = 1 if /SUBSCRIBER/;
push @lines, $_ if $flag1;
if (/NATIONAL/) {
print @lines if $flag2;
$flag1 = 0;
$flag2 = 0;
@lines = ();
}
}
__DATA__
foo
bar
SUBSCRIBER
goo
hoo
nada
NATIONAL
SUBSCRIBER
goo
A1
NATIONAL
junk
junk
junk
Prints:
SUBSCRIBER
goo
A1
NATIONAL
Update: Ok, here's my solution with Range Operators:
use strict;
use warnings;
my $flag = 0;
my @lines;
while (<DATA>) {
if (/SUBSCRIBER/ .. /NATIONAL/) {
push @lines, $_;
$flag = 1 if /A1/;
if (/NATIONAL/) {
print @lines if $flag;
$flag = 0;
@lines = ();
}
}
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.