in reply to help match this

Given two delimiters over potentially more than one line, it seems easier and more maintainable to me to separate the matching operations, for example:
my $phase = 0; my $start = '<a'; my $finish = 'NGC:003288'; my $content = ''; while( <> ) { if ( $phase == 0 ) { if ( /$start(.*)$/ ) { $phase++; $_ = $1; } else { next; } } if ( $phase == 1 ) { if ( /(.*)$finish/ ) { $content .= $1; last; } $content .= $_; } }

-M

Free your mind

Replies are listed 'Best First'.
Re^2: help match this
by bobf (Monsignor) on Jul 04, 2006 at 20:49 UTC

    In cases like this the flip-flop operator ( '..' in scalar context, see perlop) can really help to clean things up by eliminating the need to track state. For example, the entire body of your while loop can be replaced with this:

    if( /$start/ .. /$finish/ ) { $content .= $_; }
    Now that is easier and more maintainable!

    The snippet above will append $_ to $content anytime $_ matches $start and until it matches $finish. Note that $content will include the patterns within $start and $finish, however, so a simple regex at the end can be used to eliminate them:

    $content =~ m/$start(.*)$finish/s;
    This does, of course, simply reduce to the examples above which use the s modifier to allow '.' to match newlines, but it illustrates how the flip-flop operator could be used in this situation. No more need for $phase, no more funky loop control in nested 'if' statements, and no manual resetting of $_.

    See also the very nice discussion in Flipin good, or a total flop?.

      The purpose of my post was to demonstrate that it was easy enough to split the matching into two. I am normally a fan of terse code, especially if the usage of an operator is unambiguous, but because of the danger of the unwary reader confusing it with the .. range operator, this requires significant explanation which would not be germane to the simple point I was making. I don't rule it out though and will bear it in mind for such time as I can think of a way to present it easily enough to potentially beginner OPs.

      -M

      Free your mind