in reply to Writing to a New File

In order to have it properly interpreted as a number, you need to remove the leading "count=" part after having read the line from the file... — something like this

my $flashcount_file = "/var/www/html/log/flashcount.txt"; open my $flashcount, "<", $flashcount_file; my $count = <$flashcount>; $count =~ s/^count=//; # <-- remove "count=" $count++; close $flashcount; open my $flashcount, ">", $flashcount_file; print $flashcount "count=$count"; close $flashcount;

Replies are listed 'Best First'.
Re^2: Writing to a New File
by ikegami (Patriarch) on Jan 29, 2008 at 00:58 UTC

    Oh how many times have I seen this code crap out!

    You have a race condition. flock the file while you're working on it. In order to maintain the lock, you won't be able to close and reopen the file, so you'll have to open the file using in read-write mode and use seek.

    use Fcntl qw( LOCK_EX SEEK_SET ); my $flashcount_file = '/var/www/html/log/flashcount.txt'; open(my $flashcount, '+<', $flashcount_file) or die; flock($flashcount, LOCK_EX) or die; my $count = <$flashcount>; $count =~ s/^count=//; $count++; seek($flashcount, 0, SEEK_SET) or die; # Not needed in this case. truncate($flastcount, 0) or die; print $flashcount "count=$count\n";

    Untested.

    Note: The code assumes the file already exists.

    Update: Added code.