The shortest counter scripts

brian_d_foy on 2003-01-21T01:00:51

While looking for a Perl source code line counter, I ran across several web counter script. Mark Brailsford claims that he might have the shortest counter script and even uses that as part of the name: 10 Line Counter, tagged with a July 2001 date---well after anyone thought counters were interesting anymore. Still, he makes a pretty bold statement.

print "Content-type: text/html\n\n";
open (CNT, "+;
print "$number";
seek(CNT, 0, 0);
$number++;
print CNT "$number";
close(CNT);
exit;


I am not a Perl golfer and I loathe obfuscation, but Mark's script is much too long for a simple Perl script. A little script like this has no need for exit(). Perl's autoclose feature does away with the close() too. He only needs to print to two places, but has three print statements. I use the increment operator (++) inline with other statements, and remember that the result of an assignment is the assigned value.

Even without obfuscation and needing to add a line, I get the same script in half the length. Both scripts even have the same bug---they do not create the file if it exists.

open FH, '+;
seek FH, 0, 0;
print FH ++$number;


If I want to use a module, the script is almost trivial.

use File::CounterFile;
print "Content-type: text/html\n\n", File::CounterFile->new( "./count.txt", 1 )->inc;


The files created by File::CounterFile do not work with the other scripts (and the other way around, too) because the module throws in some extra magic to recognize itself.

The earliest version of File::CounterFile on CPAN is 0.12, uploaded in the middle of 1998---three years before the date in "10 Line Counter". I think Gisle not only has the shortest counter file script, but also got there first.

Even then, cry "Web" and let slip the golfers of Perl.