General discussion

Locked

Perl - read between lines in a file

By cpfeiffe ·
All,
I'm trying to find a simple way to read between lines in a file with perl.

For example a file might contain...
A
bunch of lines
B
bunch of lines
C
bunch of lines
D

And I want to read the "bunch of lines" between line B and line C.

I have the file handle and can read line by line just fine so the basic part is done. I just want to be selective on what lines I'm reading. The result goes into an array, but I only want to add lines between B and C in the array. I can do this with a couple of loops but that is messy and I'm hoping someone will have a better idea. I will know what B and C are, but not what the other lines are.

Thanks for any suggestions.

This conversation is currently closed to new comments.

3 total posts (Page 1 of 1)  
| Thread display: Collapse - | Expand +

All Comments

Collapse -

by mike.lee In reply to Perl - read between lines ...

There are a few ways to get to the bottom of this. First off depending on what system you are programming on (ultimately which character set you are using) you can look for linefeeds and carrige returns to identify the end of each line. Secondly, knowing that, use regular expressions to identify the start (b) and ending (c) points in your script. Then after identifing them, open your readline if the expression is true, set an "indicator" to reflect the state of the readline and and then close again when the indicator changes. You will need a loop to input to your array. Add one word to the array at a time or add a whole line. Regardless of how may lines/word you are placing in the array, the array space needs to be incremented while storing.
The cat in the hat.
$_[0] = "The";
$_[1] = "cat";
...
Something like this (Can't remember the exact syntax)
...
var $i = 0;
While filehandle <> EOF {
$_[$i] = readline(fileandle);
$i++;
}

Cheers & Happy Programming.

Collapse -

by cpfeiffe In reply to
Collapse -

by cpfeiffe In reply to Perl - read between lines ...

This question was closed by the author

Back to Linux Forum
3 total posts (Page 1 of 1)  

Related Forums