|
| |
CGI Scripts
|
Web Hosting Services |
delete_name.plThis script parses the information from the form The script demonstrates the difference between writing and appending to a file. Uses new functions chomp, join, delete. Illustrates the use of hashes to manipulate data, subroutines and branching conditional statements. * Note: If you haven't completed the previous exercises, names_file.txt is provided below. #!/usr/bin/perl#delete_name.pl#parse the form dataread(STDIN, $buffer,$ENV{'CONTENT_LENGTH'});$buffer =~ tr/+/ /;$buffer =~ s/\r/ /g;$buffer =~ s/\n/ /g;@pairs = split(/&/,$buffer);foreach $pair(@pairs){($key,$value)=split(/=/,$pair);$formdata{$key}.="$value";}$search1=$formdata{'search1'};$search2=$formdata{'search2'};# Open db for reading and displayopen(INFO, "names_file.txt");@array=<INFO>;close (INFO);$count=0;$continue=0;#check for matchforeach $line(@array){if($line =~ /$search1/ && $line =~ /$search2/){$continue++;}}if ($continue > 0){#convert to hashforeach $line(@array){$key=$count++;$value=$line;$names{$key}.="$value";}}else{#go to sub if continue = 0notfound();}#use join function to build value search$delete_value = $search1 . "\|" . $search2;#remove newline characterschomp $delete_value;chomp %names;#get matching key for valuewhile (($key,$value)= each(%names)){if ($value eq $delete_value){#delete key-valuedelete $names{$key};}}#Rewrite the fileopen (INFO,">names_file.txt");while (($key,$value)=each(%names)){print INFO "$value\n";}close (INFO);# Open db for reading and displayopen(INFO, "names_file.txt"); @array=<INFO>;close (INFO);print "Content-type:text/html\n\n"; #Follow with blank lineprint "<html>\n";print "<head><title></title></head>\n";print "<body>\n";print "<table border=\"1\">\n";print "<tr><th>File Contents</th></th></tr>\n";foreach $line (@array){print "<tr><td>$line</td></tr><br>\n";}print "</table>\n";print "</body>\n";print "</html>\n";#This subroutine sends a message to screen if match is not foundsub notfound {print "Content-type:text/html\n\n"; #Follow with blank lineprint "<html>\n";print "<head><title></title></head>\n";print "<body>\n";print "Not found\n";print "</body>\n";print "</html>\n";exit;}
names_file.txtIf you haven't completed the previous exercises copy this data to Notepad and save it in your C:\usr\cgi-bin directory as names_file.txt Bunyan|PaulSimpson|BartAnderson|PamelaBush|GeorgeNote: If the scripts don't work: |
Create a Website with CMS
|
| Net Success 2000 Plus Inc PO Box 1508 Somerset, KY 42502 Copyright 2000 - 2007 Net Success 2000 Plus Inc Last Modified: January 16, 2008 |