Perl Programming Page 2 - Perl 101 (part 8) - Putting It To The Test |
The first tool that we're going to discuss today is the counter. The basic purpose of a Web site counter is to record the number of people who have visited a particular page. There are four simple steps involved in building a counter: Step One: Create a text file on the server, which will store the number of visitors. Step Two: When someone visits the site, this file is accessed, the number stored within it is obtained and incremented by one, and then displayed to the visitor. Step Three: The new number is written back to the file. Step Four: Go back to Step Two. Here's the code: #!/usr/bin/perl # counter.cgi - count visitors to page # open a file handle to read the contents of the file "counter.dat" # this file contains the number of visitors before the # current user. # make sure that you have permission to write to this file open (COUNT, "counter.dat"); # assign the value that is stored in the file handle in a temporary variable $counter = <COUNT>; close (COUNT); # open the file handle to write the new number back to the file open (COUNT, "> counter.dat"); # increment the counter variable by one $counter += 1; # write the new number print COUNT "$counter"; close (COUNT); # now display the HTML code print "Content-Type: text/html\n\n"; # print the new counter value print "<html>\n<body>\n<h1>Your are visitor number $counter.</h1>\n</body>\n</html>"; And here's the output: Content-Type: text/html <html> <body> <h1>Your are visitor number 30.</h1> </body> </html> You can easily extend the functionality of this counter to store the IP address, the browser type, the referrer URL and other visitor statistics by making use of the environment variables we showed you last time.but we're going to leave that to you. This article copyright Melonfire 2000. All rights reserved.
blog comments powered by Disqus |