Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Monday January 20, 2003
08:00 PM

The shortest counter scripts

[ #10089 ]

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, "+<count.txt");
flock(CNT, 2);
$number = <CNT>;
print "$number";
seek(CNT, 0, 0);
print CNT "$number";

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, '+<count.txt';
flock FH, 2;
print "Content-type: text/html\n\n", $number = <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.