Kaye and Geoff's web page documentation 

Perl script to search a defined file for a word

The following Perl code outputs each line of a file (up to a maximum of 19) which contains a defined word. The first block of code gets the information passed from the form: the file name and the word. Then the code outputs the HTML for the start of the page which will be returned. Then there is some error checking to ensure that the file is readable and that the word contains something other than whitespace. Each line is read in turn and checked to see if it contains the word ( $line =~ /$word/) can be read as 'if line contains the word then...'). Each line which matches is counted and output to standard output, so becomes part of the returned web page. When all lines have been processed the HTML is completed.

#! /usr/bin/perl # require 'Re_sub.pm'; # # search a page for a word # # get the form information # split the imput stream into separate fields # use resub from the Re_sub.pm package to translate escaped characters # $incoming = <STDIN>; foreach $item (split (/&/, $incoming)) { ($name, $value) = split (/=/,$item); $value = &resub ($value); if ($name eq "file") { $file = $value; } if ($name eq "word") { $word = $value; } } # # output the beginning HTML # print "Content-type: text/html\n\n"; print '<html><head><title>Page searching</title></head>'; print '<body bgcolor="#ffffff">'; print '<br><br><pre>'; # # check that the file exists and can be read # ensure that there is something realistic to search for # $ok = '1'; unless (-r $file) { $ok = '0'; } ($word, $discard) = split (/\s+/, $word); unless ($word =~ /\S/) { $ok = '0'; } # # look for the word # $n = 0; if ($ok) { open (FILE, "$file"); while ($line = <FILE>) { if ($line =~ /$word/) { $n++; if ($n < 20) { print "$line"; } } } close (FILE); print "\n $n lines contained \'$word\' \n"; } else { print "Error in filename or search word \n"; } # # outout the ending HTML # print '</pre>'; print '</body></html>'; exit;