W
Wayne Fulton
A cgi counter (code that I copied from somewhere) was reseting to zero
frequently. My guess is that it was when it got to 65535, overflowing
16 bits (I am not entirely sure of that, but it seems logical).
Code was:
sub incrementCount {
$counterFile = "filenamehere.txt";
if (-e $counterFile) {
open(COUNT,"$counterFile") || die("Can't open $counterFile: $!\n");
}
$total = <COUNT>;
chop $total;
close(COUNT);
$total++;
open(COUNT,">$counterFile") || die "$0: can\'t open $counterFile:
$!\n";
print COUNT "$total\n";
close(COUNT);
}
Since perl variables are not typed, I reasoned that it was the final
print doing the 16 bit reset. I changed it to
printf (COUNT "%lu\n", $total);
and seemingly have corrected the problem - it counts past 65535 now.
Questions:
Why was it resetting in the first place? I know mostly C, but I
thought perl sensed what variable type was necessary? Why was it
truncated as short? I assume this must be a print default, but I am
unalbe to find reference to this in the Programming Perl 2nd book.
Probably a seek 0 would be more efficient than two opens/closes, but is
this %lu format as good as any way of fixing the "short" problem?
Comments appreciated. Thanks.
frequently. My guess is that it was when it got to 65535, overflowing
16 bits (I am not entirely sure of that, but it seems logical).
Code was:
sub incrementCount {
$counterFile = "filenamehere.txt";
if (-e $counterFile) {
open(COUNT,"$counterFile") || die("Can't open $counterFile: $!\n");
}
$total = <COUNT>;
chop $total;
close(COUNT);
$total++;
open(COUNT,">$counterFile") || die "$0: can\'t open $counterFile:
$!\n";
print COUNT "$total\n";
close(COUNT);
}
Since perl variables are not typed, I reasoned that it was the final
print doing the 16 bit reset. I changed it to
printf (COUNT "%lu\n", $total);
and seemingly have corrected the problem - it counts past 65535 now.
Questions:
Why was it resetting in the first place? I know mostly C, but I
thought perl sensed what variable type was necessary? Why was it
truncated as short? I assume this must be a print default, but I am
unalbe to find reference to this in the Programming Perl 2nd book.
Probably a seek 0 would be more efficient than two opens/closes, but is
this %lu format as good as any way of fixing the "short" problem?
Comments appreciated. Thanks.