Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

I still don't get locking. I just want to increment the number in the file. How can I do this?

by faq_monk (Initiate)
on Oct 13, 1999 at 03:42 UTC ( [id://806]=perlfaq nodetype: print w/replies, xml ) Need Help??

Current Perl documentation can be found at perldoc.perl.org.

Here is our local, out-dated (pre-5.6) version:

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. Better to pick a random number. It's more realistic.

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

    use Fcntl;
    sysopen(FH, "numfile", O_RDWR|O_CREAT)       or die "can't open numfile: $!";
    flock(FH, 2)                                 or die "can't flock numfile: $!";
    $num = <FH> || 0;
    seek(FH, 0, 0)                               or die "can't rewind numfile: $!";
    truncate(FH, 0)                              or die "can't truncate numfile: $!";
    (print FH $num+1, "\n")                      or die "can't write numfile: $!";
    # DO NOT UNLOCK THIS UNTIL YOU CLOSE
    close FH                                     or die "can't close numfile: $!";

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. :-)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2024-04-18 07:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found