in reply to Re: Text file got corrupted?
in thread Text file got corrupted?

Thanks, jonnyfolk!

I'm adding a snippnet of a typical modify subroutine so other monks here and yourself can help me pinpoint the problem area.

# When I test the script locally in Windows, I need # to suppress flock because it's not supported # In use in the server, $flock is set to 1. my $flock = 1; sub modify { my $tmp_file = get_file(); open(FILE,"+<$tmp_file") || error("The file $tmp_file cannot be foun +d!"); flock(FILE, 2) || die $! if $flock; chomp(my @lines = <FILE>); seek(FILE,0,0); truncate(FILE,0) || die $!; # could have used foreach here for (0..@lines) { my ($name, $score) = split/\|/, $lines[$_]; $score++; print FILE "$name|$score\n" if ($name); } close FILE; }
Please help me look at the code to see if I'm missing something :)

Replies are listed 'Best First'.
Re: Re: Re: Text file got corrupted?
by jonnyfolk (Vicar) on Oct 01, 2003 at 07:47 UTC
    Hello kiat,

    I'm sure the other monks will let me know if I am on the wrong track, but I think you may have a problem in the line flock(FILE, 2) || die $! if $flock;

    By putting in the phrase "if $flock" what you are saying is that the script should die if the lock is "shared for reading" but not if it is not locked at all! What I think would be preferable is simply:

    flock(FILE, 2) || die "can't print to $tmp_file: $!";
    as this would force the script to die on any circumstances other than a "locked for writing" situation.

    Addendum: It also seems a little strange to me that you go to the trouble of defining a variable $flock but then use flock(FILE, 2). Though I can see that you wouldn't want to mistakenly do anything else but "2" in a writing situation I would think that consistent use of one or other methods (and making sure that usage is correct in the chosen method) is better than being inconsistent and inviting anomolies to occur.