Your (main) problem is that you're matching against individual lines, i.e. 'HEADER(', next '  LIBDAT("GTASK")', and so on. In other words, the regex can never find 'HEADER...' and 'GENRE_BY...' at the same time.

One way around this would be to split the input appropriately (as shown in the snippet by GrandFather). Another way would be to use the flip-flop operator .. to accumulate the necessary lines as shown below. The expression if (/^HEADER/ .. /^\)/) is true starting with a line matching /^HEADER/ up until a line matching /^\)/, in which case you append the current line to the accumulator ($entry). Upon the next line (not being HEADER or )) the flip-flop is reset to false.

(I've put in an additional end-of-entry test (if (/^\)), so the code will correctly deal with the case where a new HEADER line is immediately following a previous entry (without any other lines in between) — if your input always has other stuff in between the entries, you could also just put the regex test directly in an else branch of the flip-flop test...)

#!/usr/bin/perl use strict; use warnings; use Getopt::Long; GetOptions( 'FileIn=s' => \my $fileIn, 'FileOut=s' => \my $fileOut, ); if ($fileIn && $fileOut) { open(INPUT,"<","$fileIn"); my $entry = ""; while (<INPUT>) { next if /^\n/; if (/^HEADER/ .. /^\)/) { # flip-flop $entry .= $_; # accumulate input } if (/^\)/) { # end of entry # check for desired type of entry if ($entry =~ /^HEADER(.*?)^\s*GENRE_BY(.*)/sm) { print $entry; } $entry = ""; # reset accumulator } } }

In reply to Re^3: Question on RE based matching by almut
in thread Question on RE based matching by noobee

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.