That is a horrible, horrible suggestion. It will work fine as long as you get only a few hits a day. But as soon as you get two hits almost simultaneously, you will have problems. If you are lucky, your counter will display a bogus number. If you are unlucky, your visitors will get a broken image icon as the number.

This is a Unix environment. That means, multitasking. It's not a PC, two things can actually happen at the same time! Hence, you need to use critical sections in your code - and lock the file. Here's a suggestion of how to tackle the problem:

use strict; use warnings 'all'; use Fcntl qw /:DEFAULT :flock :seek/; my $counter_file = "/tmp/counter"; sysopen my $fh => $counter_file, O_RDWR | O_CREAT, 0644 or die "Failed to open $counter_file: $!\n"; flock $fh => LOCK_EX or die "Failed to flock $counter_file: $!\n" +; chomp (my $counter = <$fh> || 0); $counter ++; seek $fh => 0, SEEK_SET; print $fh "$counter\n" or die "Failed to write to $counter_file: $! +\n"; truncate $fh => tell $fh or die "Failed to truncate $counter_file: $! +\n"; close $fh or die "Failed to close $counter_file: $!\n" +; ... Do whatever you want with $counter here ....
But this is just shown for educational purposes. Using counters on webpages is so mid-nineties, people have done it before, and there are ready to use programs and modules out there. And I bet Randal has a column about it....

Abigail


In reply to Re: counter by Abigail-II
in thread On server, counter file is read-only by sOKOle

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.