Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Read Between the Lines

by SuzuBell (Acolyte)
on Jul 05, 2013 at 00:03 UTC ( #1042551=perlquestion: print w/ replies, xml ) Need Help??
SuzuBell has asked for the wisdom of the Perl Monks concerning the following question:

I have many text files of the same format that I must read. The lines of interest in the text files are between two lines that are consecutive asterisks (************************). What would be an efficient way for me to only consider the lines between these two lines of asterisks?

Comment on Read Between the Lines
Replies are listed 'Best First'.
Re: Read Between the Lines
by choroba (Canon) on Jul 05, 2013 at 00:21 UTC
    You can use the flip flop operator (see Range Operators):
    while (<>) { if (/^\*+$/ ... /^\*+$/) { print "Inside: $_"; } }
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      I like it. I think the OP didn't want the asterisks themselves printed, so a small addition would clear that up:

      while (<>) { print if /^\*+$/ ... /^\*+$/ and not /^\*+$/; }
Re: Read Between the Lines
by parv (Priest) on Jul 05, 2013 at 00:32 UTC
Re: Read Between the Lines
by rjt (Deacon) on Jul 05, 2013 at 01:07 UTC

    If your file is small enough (i.e., not many megabytes in size), slurping the whole thing and using a regexp will be efficient enough, and allow you to capture multiple groups, if necessary, without matching unbalanced asterisks.

    $_ = do { local $/; <> }; print "Match: $_" for /^\*+$ (.+?) ^\*+$/smxg;

    Full example after the <readmore>.

Re: Read Between the Lines
by sundialsvc4 (Abbot) on Jul 05, 2013 at 01:54 UTC

    A more generalized way to handle such requirements is with a Finite-State Machine (FSM) approach.   The algorithms consider, not only the current line of input, but the $state that the FSM is “in” at the time, where the current value of $state is determined by recent history of lines seen.   It is probably overkill for a requirement as trivial as this one seems to be,.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1042551]
Approved by Old_Gray_Bear
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (8)
As of 2015-10-13 17:21 GMT
Find Nodes?
    Voting Booth?

    Does Humor Belong in Programming?

    Results (311 votes), past polls