#!/usr/local/bin/perl #******************************************* # Filename: phonebook.perl ** # A simple phone book application in perl ** #******************************************* # Send MIME Header print "Content-type: text/plain\n\n"; # Check the CONTENT_LENGTH environment variable $content_len = $ENV{"CONTENT_LENGTH"}; if ($content_len == 0) { print "CONTENT_LENGTH is 0."; exit(1); } # read the data into the "cgistr" variable read(STDIN, $cgistr, $content_len); # split it into an array by the "&" character @cgistr = split(/&/, $cgistr); foreach $i (0 .. $#cgistr) { # convert the "+" to space character $cgistr[$i] =~ s/\+/ /g; # convert the hex tokens to characters $cgistr[$i] =~ s/%(..)/pack("c", hex($1))/ge; # split into name and value ($name, $value) = split(/=/, $cgistr[$i],2); # create the associative element $cgistr{$name} = $value; } $found = 0; if ($cgistr{"ACTION"} eq "ADD") { &add_name; } elsif ($cgistr{"ACTION"} eq "DELETE") { &del_name; } else { &search_name; } exit(0); #************************************ # subroutine to add a name/number ** #************************************ sub add_name { if (length($cgistr{"name"}) == 0) { print "Name is required!\n"; exit(1); } if ( ! open(HNDL, ">>perl_phone.dat")) { print("Unable to open perl_phone.dat.\nContact Webmaster.\n"); exit(1); } else { print(HNDL $cgistr{"name"}, "\n", $cgistr{"number"}, "\n"); } close(HNDL); print "Entry added successfully!\n" } #************************************** # subroutine to delete a name/number ** #************************************** sub del_name { if ( ! rename("perl_phone.dat", "perl_phone.tmp")) { print "Unable to rename perl_phone.dat to perl_phone.tmp.\n"; print "Contact Webmaster.\n"; exit(1); } if ( ! open(TMPHNDL, "perl_phone.tmp")) { print "Unable to open perl_phone.tmp. Contact Webmaster.\n"; exit(1); } if ( ! open(HNDL, ">>perl_phone.dat")) { print "Unable to open perl_phone.dat. Contact Webmaster.\n"; exit(1); } while ($nameline = ) { chop($nameline); $phoneline = ; if ($nameline ne $cgistr{"name"}) { print HNDL $nameline, "\n", $phoneline; } else { $found = 1; } } close(TMPHNDL); close(HNDL); if ($found) { print "Entry successfully deleted!\n"; } else { print "Entry not found!\n"; } } #****************************************** # subroutine to search for a name/number ** #****************************************** sub search_name { if ( ! open(HNDL, "perl_phone.dat")) { print "Unable to open perl_phone.dat. Contact Webmaster.\n"; exit(1); } while ($nameline = ) { chop($nameline); $phoneline = ; if ($nameline eq $cgistr{"name"}) { print "Name = ", $nameline, "\nPhone = ", $phoneline; $found = 1; last; } } close(HNDL); if (! $found ) { print "Entry not found in the phonebook.\n"; } }