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

Discussion in 'Perl Misc' started by PerlFAQ Server, Apr 11, 2011.

  1. 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
    perlfaq.pod.
    PerlFAQ Server, Apr 11, 2011
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    104
    Views:
    10,937
    Jordan Abel
    Oct 28, 2005
  2. jalkadir
    Replies:
    2
    Views:
    366
  3. Replies:
    99
    Views:
    2,479
    eliza81
    Jun 11, 2010
  4. Alf P. Steinbach /Usenet
    Replies:
    0
    Views:
    879
    Alf P. Steinbach /Usenet
    May 22, 2011
  5. PerlFAQ Server
    Replies:
    0
    Views:
    116
    PerlFAQ Server
    Jan 7, 2011
Loading...

Share This Page