FAQ 5.23 I still don't get locking. I just want to increment the number in the file. How c...

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

This is an excerpt from the latest version perlfaq5.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .


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

            use Fcntl qw(:DEFAULT :flock);
            sysopen my $fh, "numfile", O_RDWR|O_CREAT or die "can't open
numfile: $!";
            flock $fh, LOCK_EX                        or die "can't flock
numfile: $!";
            my $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: $!";
            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. :-)


The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in

Site Timeline