It's a bad idea to save the count in the script, but
it can be done. I wrote
a CGI script to do this while exploring some
other confusion.
Here are two console scripts. The first does the
wrong thing by saving the count in itself. The
second does the right thing by using an external
data file.
As always in Perl, there are many other ways to increment
a count. Neither of these two examples is the worst or best
way to do it, they're merely bad and better.
WRONG
#!perl -w
# self-contained counter script increments and prints value in DATA
# set permissions to allow script to read and write itself - epoptai
use strict;
my$e = 0;
my$d;
while(<DATA>){$d .= $_} # read data
$d++; # increment
open (ME,"+>> $0") or die "$!"; # open self
unless($^O=~/mswin/i){ flock(ME,2) or die "$!"} # lock unless win32
my@me = <ME>; # read self into array
for(@me){
if($_=~m|_\_DATA_\_|){ $e = 1; next } # find last line
if($e == 1){ $_ =~ s/\d+/$d/o } # and replace with incremented val
+ue
}
seek ME, 0, 0; # goto top of self
truncate ME, 0; # and clear it
print ME @me; # write modified contents
close ME or die "$!";
print $d; # print incremented value
__DATA__
0
RIGHT
#!perl -w
# counter script increments and prints value in $file
# set permissions to allow script to read and write $file - epoptai
use strict;
my$file = 'count.txt';
open (FILE,"+>> $file") or die "$!"; # open file
unless($^O=~/mswin/i){ flock(FILE,2) or die "$!"} # lock unless win32
local $/ = undef;
my$num = <FILE>; # read file into array
$num++;
seek FILE, 0, 0; # goto top of file
truncate FILE, 0; # and clear it
print FILE $num; # write modified contents
close FILE or die "$!";
print $num; # print incremented value
|