Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

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?

Replies are listed 'Best First'.
Re: Read Between the Lines
by choroba (Bishop) 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 all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2018-06-21 18:37 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (118 votes). Check out past polls.