Tuesday, December 21, 2004

Perl, touch and silly hit counters

While looking at how to set a file's time stamp in Perl (Perl's `touch`), I stumbled across this in the perl faq:

I still don't get locking. I just want to increment the number in the file. How can I do this?
Didn't anyone ever tell you web-page hit counters were useless?
They don't count number of hits, they're a waste of time, and they serve only to stroke the writer's vanity. It's better to pick a random number; they're more realistic.

Anyway, this is what you can do if you can't help yourself.

[8 lines of boring and ugly code]

Here's a much better web-page hit counter:

$hits = int( (time() - 850_000_000) / rand(1_000) );

If the count doesn't impress your friends, then the code might.

Well, it did amuse me. So much indeed, that I'm actually about to add a page counter to http://alma.ch/perl.

Oh, and by the way: `touch` in Perl is utime in case that is what actually brought you here.

Update (since this little entry seems to rank strangely high for "Perl touch" searches):

As POS points out in a comment below, utime will not create the file if needed, as `touch` would. To update-or-create, try something like utime(time, time, "file") or ( open(F, ">file") && close F )

For a real `touch` clone, you probably need a little function, or even the big one from the Perl Power Tools project.