#!/usr/bin/perl -w # Summary: (Very) simple CGI to count occurences of a string in a file. # Author: Chris Ball. # Variables: Takes $file, $search_string from CGI. Changes/prints $counter. use CGI qw/:standard/; # Include CGI. use strict; # Turn warnings on. my ($filename, $search_string, $counter); # Initialise variables. # Going to print the HTML page before input. Comments contain the html tags. print header, # Print the HTTP headers. start_html('File Searcher'), # , , h1('File Searcher'), #

start_form, #
"File to search: ", textfield('filename'), # br, #
"String to search for: ", textfield('search_string'), # p, #

submit, # end_form, #

hr; #
# Right. Now, if we're called with 'filled-in boxes' (param()), do this as well. if ( param() ) { $filename = param('filename'); # Set local variables to the input $search_string = param('search_string'); # on the form. if ( ! -f $filename || -z $filename ) { # Is the file empty or nonexistant? print "I couldn't find $filename. Sorry!", p, hr, end_html; } else { # The file exists and isn't empty. # The actual processing of the script happens here. We search through # the file for a match, and increment a variable if we find it. open(FILE, "<$filename"); # open $filename for reading. while () { # read a line of the file. $counter++ if m/$search_string/; # increment $counter if match. } # go back to the while (next line). close(FILE); # reached EOF - close the file. # Right. We've got the number of matches of our string in $counter. # Let's print the rest of the page. print "You searched for $search_string in $filename.", p; if ($counter > 0) { print "I had a look, and found it $counter time(s). Nifty."; } else { print ".. but I couldn't find it. Sorry!"; } print hr, end_html; # wrap up the html.. } }