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:
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.#!/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
(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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |