When I ran your code, I had different results that I
always had the first ten lines appended to the log file.
The code below, acts as expected though I need to
look into my open statements to make sure it
doesn't clobber the lock.
I replaced the while loop with a for loop and the foreach
loop with a simple print join.
#!/usr/bin/perl
use strict;
use warnings;
my $logfile = "logfile";
my @entries;
open(LOG, "<$logfile") || die "Could not open $logfile reading\n";
flock(LOG, LOCK_EX) || die "Could not lock file $!\n";
for (1..10) {
chomp($_ = <LOG>);
push @entries, $_;
}
#Do something with @entries
# open(LOG, ">$logfile") || die "Could not open $logfile for writing\
+n";
truncate(LOG, 0);
print LOG join("\n", @entries), "\n";
close(LOG);
Update: Instead of the reopen, use
truncate with the other open
"+<"
Further Update: Fixed that before
bluto's good advice after a bit of looking up some info.
Knew the close would happen, wasn't positive it would
kill the lock though. Hence, my warning up above. Also means the unlocking flock is
unnessasry since the lock is released on close.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.