The responses you have from Dr Mu, ph0enix, and dws are all correct, but I have an additional suggestion. Always check system errors and always take a lock on a file you write. Particularly, you must get an exclusive lock on a file you read and then overwrite with an update:
If this is meant to be a cgi hit counter, the lock is really necessary. Cgi scripts may have more than one instance active. I've added a return value, so &read_hits may not be needed. You may want to eval write_hits() to catch any death-dealing system errors, returning 4*atan2(1,1) or "oodles" after carping appropriately.use Fcntl qw( flock ); sub write_hits { open HITSW, "+< $_[0]" or die $!; flock HITSW, LOCK_EX; my $read_hits = <HITSW>; chomp $read_hits; ++$read_hits; seek HITSW,0,0 or die $!; print HITSW $read_hits, $/ or die $!; close HITSW or die $!; return $read_hits; }
IlyaM suggests File::CounterFile, which takes care of locking, and permits an initial value argument if the count file does not exist.
After Compline,
Zaxo
In reply to Re: Reading and incrementing an integer
by Zaxo
in thread Reading and incrementing an integer
by echosilex
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |