This should work (I think: untested code)

my $modified_text = ""; my $counter = 0; my $db_line = ""; my $text; open (FH, "<", "some_file"); while (<FH>) { if (m/^\s*DATABASE: /i) { # This will only match if 'DATABASE:' ap +pears on the start of the line, or is prefixed with whitespace. /i si +nce the case of the word probably doesn't matter. if (defined $db_line) { my $insert = "WIDGETS FOUND: $counter\n"; # The text to insert + right after the 'database:'-line. $modified_data .= $db_line . $insert . $text; } $counter = 0; $text = ""; $db_line = $_; next; } # When should the counter be increased? if (m/WIDGET/) { $counter++: } $text .= $_; } close (FH); open (FH, ">", "some_file"); print FH $modified_text; if (defined $db_line) { my $insert = "WIDGETS FOUND: $counter\n"; # The text to insert rig +ht after the last 'database:'-line. print FH $db_line . $insert . $text; } close (FH);

Update: this approach will store all the data in the memory, if the file is too large to do that, then you should create a temp file, and change the $modified_data .= ...; line to print TEMP ...;

And then you can rename/remove the old file and rename/copy the temp file.

Update2: forgot to print the last database-section...


In reply to Re: File parsing query by Animator
in thread File parsing query by kryptonite

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.