G'day perlato,

Welcome to the Monastery.

It looks like you were doing fine up to the flip-flop conditional (if (/TRANSACTION STARTED/ .. /TRANSACTION END/) {...}) and then got a bit lost.

You can do all the remaining processing within that if block. Here you'll want to do one of three things:

  1. If /TRANSACTION STARTED/ is TRUE, open a new file for writing. (Don't output the line.)
  2. If /TRANSACTION END/ is TRUE, close the filehandle. (Don't output the line.)
  3. Output all lines that don't match either condition in 1 or 2.

The coding required is very straightforward:

#!/usr/bin/env perl use strict; use warnings; use autodie; my $filename_prefix = 'pm_1155986_out_'; my $filename_suffix = '.txt'; my $filename_number = 0; my $out_fh; my ($start_re, $end_re) = (qr{TRANSACTION STARTED}, qr{TRANSACTION END +}); open my $in_fh, '<', 'pm_1155986_in.txt'; while (<$in_fh>) { if (/$start_re/ .. /$end_re/) { if (/$start_re/) { open $out_fh, '>', $filename_prefix . $filename_number++ . $filename_suff +ix; next; } if (/$end_re/) { close $out_fh; next; } print $out_fh $_; } }

[Note I've used the autodie pragma. This avoids having to hand-craft ... or die "..." messages for all the I/O operations: a tedious and error-prone activity (which Perl will do for you if you ask it nicely).]

Here's all the input and output data (within the spoiler):

— Ken


In reply to Re: Extract ranges of lines from a file, saving each range to a separate file by kcott
in thread Extract ranges of lines from a file, saving each range to a separate file by perlato

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.