Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

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 (Chancellor) 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
[Tux]: when I set QT_IM_MODULE and GTK_IM_MODULE both to c<xim> and *unset* XMODIFIERS, all works fantastic
Tux => $HOME
[Tanktalus]: great, now I'm going to have to convert html codes to text for display... :)

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (12)
As of 2017-09-25 21:16 GMT
Find Nodes?
    Voting Booth?
    During the recent solar eclipse, I:

    Results (291 votes). Check out past polls.