Perlaccess : Tutorials : Examples
Examples: Access Counters (7.1)
by Brett Roberts
http://www.bigresources.com

Simple Access Counter
In this example i will dissect a popular access counter written in perl to show you the different aspects of the code. The best tool for me when learning a new language is studying existing code. If you can follow the logic behind a certain programming language, it is easy to learn the syntax later. Enjoy!

# Example: Cliff's Counter Script

# initializing variables for later use

1- $logpath = "/server/path/to/count.html";
# where access data is kept

2- $visible = 1;
# show counter or not?

3- $pad = 5;
# number of digits for your counter

# below is the main processing

4- open (LOG, "$logpath");
5- @data = <LOG>;
6- close(LOG);

# keep following (#7) on 1 line...do no wrap

7- $url = "<tr><td align=\"right\"><a href=\"$ENV{'DOCUMENT_URI'}\">
$ENV{'DOCUMENT_URI'}</a>:</td>";

8- $count = 0;
9- $pad = "%.$pad"."d";
10- open (LOG, ">$logpath");

11- foreach $line(@data) {
12-     if ($line =~ /$url/) {
13-       $line =~ /<td>(.*)<\/td>/;
14-       $count = $1;
15-       $count++;
16-       $count = sprintf($pad, $count);
17-       print LOG "$url<td>$count</td></tr>\n";
18-    }
19-    elsif ($count == 0 && substr($line,0,8) eq "</table>") {
20-       $count++;
21-       $count = sprintf($pad, $count);
22-       print LOG "$url<td>$count</td></tr>\n";
23-       print LOG "$line";
24-   }
25-   else {
26-     print LOG "$line";
27-   }
28-}
29- close(LOG);
30- if ($visible) {
31-     print "Content-type: text/html\n\n";
32-     print "$count";
33- }


Explanation:

#1-3 = Initializing variables for easy customization of the user (webmaster) setting this script up
#4 = Opens the log file to read in data
#5 = Puts the read data into @data
#6 = Closes the log file once finished
#7 = Initializes the variable $url with a table row for easy use later in the script
#8 = Initializes the count variable to 0 before it enters into the foreach loop for each line of the log file
#10 = Opens the log file to be written to this time
#11 = for each block cycles through the lines in the log file
#12-17 = processes certain statements to format the html tables for the output of the log file...it then accumulates the count variable to calculate the amount of hits for the entry being added to the file...after calculation it then writes the line to the log file for storage
#19-26 = processes the other conditional statements based on certain aspects of the logic set for the end result writing to the log file
#29 = closes the log file because it is finished writing to the file
#30-33 = based on the value you set in $visible at the top of the script...the counter will be displayed or not.... 1=display 0=not