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

I was wondering what would be best way to read a part of
text file within specified nested markers

A sample file would look like -

RULE=1
BEGIN
INDICATOR1=BEGIN
A
B
C
INDICATOR1=END
INDICATOR2=BEGIN
E
F
G
INDICATOR2=END
END

RULE=2
BEGIN
INDICATOR1=BEGIN
X
Y
Z
INDICATOR1=END
INDICATOR2=BEGIN
W
U
V
INDICATOR2=END
END

I would like to read the text based on matching RULE and subsequently start reading values when it encounters the BEGIN. It will then store values into certain variables based on the inner INDICATOR markers. It will stop reading the file once it reaches the outer END marker.

  • Comment on Reading a part of text file between markers

Replies are listed 'Best First'.
Re: Reading a part of text file between markers
by Fletch (Bishop) on Mar 28, 2005 at 16:48 UTC

    Well, judging by the code you've written so far . . . oh, nevermind.

    Setup a variable to keep track of what state you're in. Read the file line by line. If it's a matching rule, set the state to 'looking for begin'. If you're looking for begin and see a begin, set the state to 'seen begin'. If you've seen a begin and it's an end line, set the state back to 'looking for rule'; otherwise process the line and stick whatever results wherever apropriate.

Re: Reading a part of text file between markers
by manav (Scribe) on Mar 28, 2005 at 16:56 UTC
    You can use the .. operator like
    use strict ; use warnings ; my $rule=1 ; while(<DATA>) { if(/RULE=$rule/../^END$/) { print } }
    This will only print data for RULE=1. Inside the if loop, you can do whatever you'd like with $_.


    Manav
Re: Reading a part of text file between markers
by ambs (Pilgrim) on Mar 28, 2005 at 16:48 UTC
    A first idea:
    $/="\nEND\n"; while(<>) { # $_ contains a complete rule }

    Alberto Simões