Hello usertest,

As I understand it, you want to retain all lines that do not come between START and END, and also those that do whenever def doesn’t appear in the same block; but when def does occur between START and END, you want to exclude that entire block of data.

If this is correct, then you need to store all the lines in each START ... END block (e.g., in an array), and print them if and only if it turns out that the block doesn’t contain def. For keeping track of whether you’re currently in a block, the range operator in scalar context is the most appropriate tool:

#! perl use strict; use warnings; my ($found, @lines); while (<DATA>) { if (my $flag = /START/ .. /END/) { $found = /def/ unless $found; push @lines, $_; if ($flag =~ /E0$/) { if ($found) { $found = 0; } else { print for @lines; } @lines = (); } } else { print; } } __DATA__ Source Data START abc def ghi END START xyz abc END

Output:

14:22 >perl 1646_SoPW.pl Source Data START xyz abc END 14:22 >

For the range operator, see perlop#Range-Operators.

Update: Fixed logic error in code by moving the @lines = (); statement to below the inner if ... else block; also improved wording slightly.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


In reply to Re: Perl code help by Athanasius
in thread Perl code help by usertest

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.