CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Counter

 



Gzaector
Deleted

Jul 18, 2000, 11:17 PM

Post #1 of 4 (372 views)
Counter Can't Post

Ok,
I am writing a text counter cgi for my site and well im not sure how to do it. So far I have a cgi that opens a file called counter.log adds 1 to thw value in counter.log saves the added number in a variable and saves the variable in counter.log. now how do I get the variable on my index.html page?


Cretep
User

Jul 19, 2000, 12:22 AM

Post #2 of 4 (372 views)
Re: Counter [In reply to] Can't Post

Great just what we need, another couter Wink. Ok heres what you do use an SSI tag like this <!-- #exec cgi="/cgi-bin/script.pl?show" -->

then add this to your script.

if ($ENV{'query_string'} eq "show"){
&show;
}else{
&count;
}

sub show {
open (FILE, "couter.log");
$hits = <FILE>;
close (FILE);
print "$hits";
}

sub count {
#your code here
}


Gzaector
Deleted

Jul 19, 2000, 9:18 AM

Post #3 of 4 (372 views)
Re: Counter [In reply to] Can't Post

So does this look right#!usr/local/bin/perl
#
#2000 John Richards
#
if ($ENV{'query_string'} eq "show"){
&show;
}else{
&count;
}
sub show {
open (FILE, "counter.log");
$hits = <FILE>;
$hits++;
close (FILE);
print "$hits";
}
sub count {
open (RETRIEVECOUNTERLOG,"<counter.log");
$counter = <RETRIEVECOUNTERLOG>;
close (RETRIEVECOUNTERLOG);
$counter++;
open (ADDCOUNTERLOG,">counter.log");
print ADDCOUNTERLOG($counter);
close ADDCOUNTERLOG
}




Kanji
User

Jul 19, 2000, 6:29 PM

Post #4 of 4 (372 views)
Re: Counter [In reply to] Can't Post

What happens when you get two visitors within milliseconds of each other, so that you have one script $counter = <RETRIEVECOUNTERLOG>;ing while the other is open (ADDCOUNTERLOG,">counter.log");ing?

You end up breaking your script, resetting the counter back to 1.

You'd be much better off not reinventing the wheel and using something like File::CounterFile, which employs flock on the systems that support it to make sure things work right.

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

#!/usr/bin/perl

use File::CounterFile

my $counter = File::CounterFile->new( "/path/to/counter.log", 0 );

print $ENV{'query_string'} eq "show"
? $counter->value
: $counter->inc;</pre><HR></BLOCKQUOTE>

If you're wondering, those last three lines act like an if / else. You can read more about it by seeing the Conditional Operator docs. : )

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives