I think the other replies have nailed the immediate problem, but here are some extra thoughts...

1. You don't seem to be replacing the original file with any sort of modified output, so there doesn't seem to be a need to use flock on the input file. (Did you want to replace the input file, too? There's an easy way to do that without needing flock.)

2. Basic loop over the input file data can be a lot simpler, and since you're reading the whole file into memory anyway, you might as well just hold the initial and final parts in memory until you're ready to write the edited version of the input -- I don't quite see why you need the two extra temp files.

How about something like this:

#!/usr/bin/perl my $datafile = "sample.pm"; open( I, $datafile ) or die "open failed on $datafile: $!"; my @editable; my ( $bgn, $end ) = ( '', '' ); my $save = \$bgn; while (<I>) { if ( defined( $save )) { $$save .= $_; $save = undef if ( /^\#\s+__START_CONFIG__/ ); } elsif ( /^\#\s+__END_CONFIG__/ ) { $end .= $_; $save = \$end; } else { push @editable, $_; } } # $bgn holds all input up to and including "# __START_CONFIG__" # $end holds "# __END_CONFIG__ and all input that follows it # @editable holds all lines between $bgn and $end
You can save $bgn and $end to temp files if you feel the need, but I'll bet you can just hold onto those two scalars until you need to write the output file.

(And if you're going to replace the original input and want to avoid any risk that someone might read a partially-written version, just save the output to some other file name, and when that file is safely closed, just  rename $newdatafile, $datafile;)


In reply to Re: Splitting up file by graff
in thread Splitting up file by hmag

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.