Solved

I need a script that can search (and return results) from two external text files.

Posted on 2000-03-06
2
122 Views
Last Modified: 2010-03-05
I need a script that can search (and return results) from two external text files. This needs to be two scripts (similar) for two different (yet similar) text files with names, email addresses, etc. Please also provide comments regarding what the script is doing, etc.

Here is a same of the text file:

999,123456789,GARY,GORDON,WEB DEVELOPER,MIS DEPT., R 31,3539,,,,,,,GGORDON2,

Any questions, please reply.



0
Comment
Question by:garymg44
2 Comments
 
LVL 16

Accepted Solution

by:
maneshr earned 315 total points
ID: 2588283
Here is the solution.

NOTE: Remeber to change the dir path and URL's to your own values.


=============students.html
<HTML>
<HEAD>
   <TITLE>Student Directory</TITLE>
</HEAD>
<BODY TEXT="#000000" BGCOLOR="#FFFFFF" LINK="#8080FF" VLINK="#8000FF" ALINK="#F
F0000" BACKGROUND="">

<CENTER>
<CENTER>
<FORM Method="GET" Action="/cgi-bin/students.pl" NAME="SearchForm">
<FONT COLOR="#006633"><B>Enter search text:&nbsp;</B></FONT>
<INPUT NAME="search" TYPE="TEXT"><P>

<FONT COLOR="#006633"><B>NOTE: Only First name, Last name and Email id's will b
e searched!!</B></FONT><P>

<INPUT TYPE="SUBMIT" VALUE="Find Now!!">&nbsp;&nbsp;&nbsp;&nbsp;
<INPUT TYPE="RESET" VALUE="Clear Form">

<P>
<a href="/manesh/search.html">Back to Main Search Page</a>

</CENTER>
</FORM>
</BODY>
</HTML>
===================faculty.html
<HTML>
<HEAD>
   <TITLE>Faculty Directory Search</TITLE>
</HEAD>
<BODY TEXT="#000000" BGCOLOR="#FFFFFF" LINK="#8080FF" VLINK="#8000FF" ALINK="#F
F0000" BACKGROUND="">

<CENTER>
<CENTER>
<FORM Method="GET" Action="/cgi-bin/phones.pl" NAME="SearchForm">
<FONT COLOR="#006633"><B>To search Database enter text:&nbsp;</B></FONT>
<INPUT NAME="search" TYPE="TEXT"><P>

<FONT COLOR="#006633"><B>Search in:&nbsp;</B></FONT>
<INPUT TYPE=RADIO NAME="field" value="3" checked>Last Name
<INPUT TYPE=RADIO NAME="field" value="4">Title/Designation
<INPUT TYPE=RADIO NAME="field" value="5">Department
<!--<INPUT TYPE=RADIO NAME="field" value="*" checked>All-->
<P>

<FONT COLOR="#006633"><B>NOTE: the results will be sorted on the field that you
 are searching in. <BR>If you search in "All", the results will be sorted by "L
ast Name"</B></FONT><P>


<INPUT TYPE="SUBMIT" VALUE="Find Now!!">&nbsp;&nbsp;&nbsp;&nbsp;
<INPUT TYPE="RESET" VALUE="Clear Form">
<P>
<a href="/manesh/search.html">Back to Main Search Page</a>
</CENTER>
</FORM>
</BODY>
</HTML>
===============phones.pl
#!/usr/local/bin/perl

##############################################################
# Author : Manesh Rao
# Date : 02/23/2000
# Purpose : To search the Faculty Phone Directory &
# based on the search condition sort & return the results.
# Change History : <Date> <Name> <Change Description>
##############################################################

use CGI;

## Read the incoming HTML Form variables
$query=new CGI; ## Create a new CGI object

$search=$query->param('search'); ## Get the user's input from the ..
$field=$query->param('field'); ##  ... form into the PERL variables

## Escape the * char from the user entered search string.
## You can add to this list other characters too!!
$search=~ s/\*/\\\*/g;

print "Content-type: text/html\n\n";

$BasedirTxt = "/home/webuser/manesh/tmp/gary"; ## The directory where the text file is located
$Myfile = "$BasedirTxt/phonedir.txt";

&ReadData; ## Read the data from the text file

$NumRecs = scalar @DirData; ## Number of data items in database OR lines in the text file
$Delimiter =","; ## De-limiter/Separator for data fields

&Header; ## Show the Page Header, Logo etc..

$matches=&FindMyString($search,$field); ## Search for the user specified text in the proper area (Last
Name, Dept., Designation/Title or All)

&PrintSearchStats($NumRecs,$matches,$search,$field); ## Print the Search Statistics

&Footer; ## Show the Footer at the bottom of the Page

############## All sub-routines are defined here #################
#----------------- Beginning of FindMyString ----------------------
## This sub-routine receives 2 parameters viz. the Search String
## ... & the Field to search in (Last Name/Title/Dept)
sub FindMyString{
($SearchString,$SearchField)=@_; ## Collect the paramters
$NumHits = 0;
$start_col=0;
$end_col=0;

if (length($SearchString) == 0 || $SearchString=~ /^\s+$/){ ## User did not enter anything or just put
in spaces!!
$NumHits = 0; ## No search required!!
}else{ ## User Provided some valid input

## The following helps us determine if a column is to be searched
## ... searched (for Last Name, Title/Designation, Dept.)
## ... OR each-and-every column is to be searched (for All)
if ($SearchField=~ /^\d$/){ ## Search in Title, Last Name or Dept.
$start_col=$SearchField;## The first column to start searching in ...
$end_col=$SearchField; ## ... & the last column to stop searching
}else{ ## This is for Search in ALL. We have removed this feature!!
$start_col=0; ## First column to ..
$end_col=15; ## ..Last column
}

## Start searching
foreach $rec ($[ .. $#DirData){ ## From element 0 to the last element
## Split every line of the Phone Dir. into fields ...
## ... & then search in the column that the user specified
@tmp=split(/$Delimiter/,$DirData[$rec]);

## NOTE the value of start_col & end_col is determined...
## ... by the what column the user wants to "Search in"
foreach $c ($start_col .. $end_col){

$tmp[c]=~ s/^\s+//g; ## Remove Leading spaces
$tmp[c]=~ s/\s+$//g; ## Remove Trailing spaces

## NOTE: We want the searching to be at the beginning ...
## ... of the column we are searching, so prepend a ^
$SearchString="^".$SearchString if ($start_col == $end_col);

if ($tmp[$c]=~ /$SearchString/i){ ## A MATCH IS FOUND!!
push(@matches,$DirData[$rec]); ## Save that line in an array
## The next line is ONLY for "Search in ALL"
## In that case a single match is enough.
## We dont have to search the remaining columns ..
## .. if the earlier column has the matching string
last if ($SearchField!~ /^\d$/);
}
}
}
## End searching

$NumHits=scalar @matches; ## No of matches = no of elements in the matches array

## Search is complete. Now check if any matches have been found
if($NumHits == 0) {return($NumHits);} ## No matches found

## Sort the results on the given column
##  Column num (starting from 1), type of sort
##  n = numeric, a = alphabetic & Array to sort
if ($SearchField=~ /^(\d)$/){ ## Search in Title, Last Name or Dept.
$sort_col=$1+1;
@matches=&my_sort($sort_col,"a",@matches);
}else{ ## For Search in ALL. We have removed this feature!!
@matches=&my_sort(4,"a",@matches); ## When user selects to search in "All" sort on Last Name
}
## End of Sort the results on the given column

## Start printing the results as a HTML Table
print "<caption><h1>Search Results</h1></caption>\n" ,
"<table border=2>\n" ,
    "<br><td>First</th>\n" ,
    "<td>Last</th>\n" ,
    "<td>Title</th>\n" ,
    "<td>Department</th>\n" ,
    "<td>Loc.</th>\n" ,
    "<td>Ext.</th>\n" ,
    "<td>E-mail</th> <tr>\n" if($NumHits > 0);

## Display the successfull matches in a HTML Table.
## Only some columns are to be displayed
foreach(@matches){
$Email="";
@tmp=split(/$Delimiter/,$_);

foreach $col_no (2..7){ ## Only columns 2 thru 7 are to be displayed
print "<td><small> $tmp[$col_no]</td></small>";
}

## The following is for people who dont have Email id's.
if (scalar @tmp>=15){
$Email=$tmp[$#tmp] ;
print "<td><small><A HREF=\"mailto:$Email\@njcu.edu\">",$Email,"</A></td></small>\n"; ## Print
the Email column
}else{ ## These People do not have an Email id :-(
print "<td><small></TD></small>\n"; ## Print a blank Email column for users without email
}

print "<tr>\n";
}

## Close the HTML Table
print "</table></center></font>\n"  if($NumHits > 0);
}

return ($NumHits); ## return the number of matches found
}
#----------------- End of FindMyString -------------------------------

#----------------- Beginning of PrintSearchStats ---------------------
## This sub-routine receives 4 parameters viz. the total no of ...
## ... records in the text file, no of matches found for the ...
## ... search string specified, the search string itself ...
## ... & the Field to search in (Last Name/Title/Dept)
sub PrintSearchStats{
($NumRecs,$matches,$search,$field)=@_;

## Earlier we had escape the * char using the \, but ...
## ... the \ char itself must be removed.
$search=~ s/\\//g; ## Remove any Escape chars.

## Actually when the user says Search in "Last Name" ...
## ... this script receives a number viz 3. Similiar is the case ...
## ... with Title/Designation (4) & Department (5).
## This number is no ordinary number but is the column number of
## that column in out text file. The columns start with 0.
## We have removed the All feature!!
## Hash which has the column no as its key & Column description as its value
%search_in=("3","Last Name",
"4","Title/Designation",
"5","Department",
"*","All"
);

print "<P>String searched =  $search\n";
print "<BR>Searched in = $search_in{$field}\n";
print "<BR>Records searched = $NumRecs\n";
print "<BR>Records matched = $matches\n";
  if($matches == 0){ ## No matches found!!
print "<BR><FONT COLOR=red>Verify spelling</FONT>\n";
}

return 0;
}
#------------------- End of PrintSearchStats ------------------------

#------------------- Start of Footer --------------------------------
sub Footer{
## Print the Footer of the Results page
print "<center>\n";
print "<br><a href=\"/manesh/faculty.html\">Back to Search Page</a>\n";
print "</center>\n";
print "<br></font></body></html>\n";
}
#------------------- End of Footer ----------------------------------

#---------------- Beginning of ReadData -----------------------------
sub ReadData{
## Open the Phone Directory text file
open(DatFil,"$Myfile"); ## Open the Phone Directory file
## Read the ENTIRE file and store the contents ...
## ... of the file in an array. Every line of the file ...
## ... becomes one element of the array!!
@DirData = <DatFil>; ## Read the ENTIRE file & store each line of the file as an element of the array
close DatFil;

chop(@DirData); ## Remove the last character from the array
pop(@DirData); ## Remove the LAST line, since it not a valid record
}
#----------------- End of ReadData ----------------------------------

#----------------- Beginning of Header-------------------------------
sub Header{
## Print the Header of the Results page
print qq{
<html>
<BODY BGCOLOR="#FFFFFF">
<head><align=right>
<title> NEW JERSEY CITY UNIVERSITY </title>

</head>
<font color="#006633">
<center><h1>NEW JERSEY CITY UNIVERSITY </h1></center>
<center><h2> Campus Directory Update</h2></center>
};
}

sub my_sort{
($col,$type,@arr)=@_;

$col--;
$type="a" if $type!~ /^n$/i; ## Default Alphabetic sort

foreach(@arr){
@tmp=split(/,/,$_);
return 0 if ($col<0 || $col>(scalar @tmp)); ## Invalid col no.
$new_arr=join(',',$tmp[$col],$_);
push(@new_arr,$new_arr);
}

if ($type=~ /^n$/i){ ## Numeric Sort
@new_arr=sort bynum @new_arr
}else{
@new_arr=sort byalp @new_arr
}

@arr=""; ## Re initialize the array
foreach(@new_arr){
@tmp=split(/,/,$_);
shift(@tmp); ## Remove the 1st column
$new_arr=join(',',@tmp);
push(@arr,$new_arr);
}

return @arr;
}

sub bynum{ $a <=> $b;}

sub byalp{ $a cmp $b;}

==================students.pl
#!/usr/local/bin/perl

use CGI;
$|++;

$query=new CGI; ## Create a new CGI object

$search=$query->param('search'); ## Get the user's input from the ..
$field=$query->param('field'); ##  ... form into the PERL variables

$search=~ s/\*/\\\*/g;

print "Content-type: text/html\n\n";

$BasedirTxt = "/home/webuser/manesh/tmp/gary"; ## The directory where the text file is located
$Myfile = "$BasedirTxt/studir.txt";

&ReadData; ## Read the data from the text file

$NumRecs = scalar @DirData; ## Number of data items in database
$Delimiter =","; ## De-limiter/Separator for data fields

&Header; ## Show the Page Header, Logo etc..

$matches=&FindMyString($search,$field); ## Search for the user specified text in the proper area (Last
Name, Dept., Designation/Title or All)

&PrintSearchStats($NumRecs,$matches,$search,$field); ## Print the Search Statistics

&Footer; ## Show the Footer at the bottom of the Page

############## All sub-routines are defined here #################
#----------------- Beginning of FindMyString ----------------------
sub FindMyString{
($SearchString,$SearchField)=@_; ## Collect the paramters
$NumHits = 0;
$start_col=0;
$end_col=0;

if (length($SearchString) == 0 || $SearchString=~ /^\s+$/){ ## User did not enter anything or just put
in spaces!!
$NumHits = 0; ## No search required!!
}else{ ## User Provided some valid input

## The following helps us determine if a column is to be searched
## ... searched (for First Name, Last Name, Email id)
$start_col=0; ## First column to ..
$end_col=15; ## ..Last column

## Start searching
foreach $rec ($[ .. $#DirData){ ## From element 0 to the last element
## Split every line of the Phone Dir. into fields ...
## ... & then search in the column that the user specified
@tmp=split(/$Delimiter/,$DirData[$rec]);

next if (scalar(@tmp) <12); ## ONLY search in students records

## NOTE the value of start_col & end_col is determined...
## ... by the what column the user wants to "Search in"
foreach $c ($start_col .. $end_col){

next if ($c != 1); ## SEARCH ONLY in LAST NAME, ignore the rest

$tmp[$c]=~ s/^\s+//g;
$tmp[$c]=~ s/\s+$//g;

if ($tmp[$c]=~ /^$SearchString/i){ ## A MATCH IS FOUND!!
push(@matches,$DirData[$rec]); ## Save that line
## The next line is ONLY for "Search in ALL"
## In that case a single match is enough.
## We dont have to search the remaining columns ..
## .. if the earlier column has the matching string
last if ($SearchField!~ /^\d$/);
}
}
}
## End searching
$NumHits=scalar @matches; ## No of matches = no of elements in the matches array

## Search is complete. Now check if any matches have been found
if($NumHits == 0) {return($NumHits);} ## No matches found

## Sort the results on the given column
##  Column num (starting from 1), type of sort
##  n = numeric, a = alphabetic & Array to sort
@matches=&my_sort(2,"a",@matches);
## End of Sort the results on the given column

## Start printing the results as a HTML Table
print "<caption><h1>Search Results</h1></caption>\n" ,
"<table border=2>\n" ,
    "<br><td>Last<br>Name</th>\n" ,
    "<td>First<br>Name</th>\n" ,
    "<td>E-mail</th>\n<tr>\n" if($NumHits > 0);

## Display the successfull matches in a HTML Table.
## Only some columns are to be displayed
foreach(@matches){
$Email="";
@tmp=split(/$Delimiter/,$_);
#------------- print   certain fields  ------------
foreach $col_no (1,2,4){ ## Only Last Name, First Name & Email prefix are to be shown
print "<td><small><a
href=\"mailto:\"$tmp[$col_no]\@njcu.edu\">$tmp[$col_no]\@njcu.edu</a></td></small>" if $col_no ==
4 && $tmp[$col_no];
print "<td><small>$tmp[$col_no]</td></small>" if $col_no == 4 && !$tmp[$col_no];
print "<td><small>$tmp[$col_no]</td></small>" if $col_no != 4;
}

## The following will take care of people who dont have Email ids'
if (scalar @tmp>=15){
$Email=$tmp[$#tmp] ;
print "<td><small><A HREF=\"mailto:$Email\@njcu.edu\">",$Email,"</A></td></small>\n"; ## Print
the Email column
}else{
print "<td><small></TD></small>\n"; ## Print a blank Email column for users without email
}

print "<tr>\n";
}

## Close the HTML Table
print "</table></center></font>\n"  if($NumHits > 0);
}

return ($NumHits);
}
#----------------- End of FindMyString -------------------------------

#----------------- Beginning of PrintSearchStats ---------------------
sub PrintSearchStats{
($NumRecs,$matches,$search,$field)=@_;

$search=~ s/\\//g;
## Hash which has the column no as its key & Column description as its value
%search_in=("3","Last Name",
"4","Title/Designation",
"5","Department",
"*","All"
);

print "<P>String searched =  $search\n";
print "<BR>Searched in = Last Name, First Name & Email idn";
print "<BR>Records searched = $NumRecs\n";
print "<BR>Records matched = $matches\n";
  if($matches == 0){ ## No matches found!!
print "<BR><FONT COLOR=red>Verify spelling</FONT>\n";
}

return 0;
}
#------------------- End of PrintSearchStats ------------------------

#------------------- Start of Footer --------------------------------
sub Footer{
print "<center>\n";
print "<br><a href=\"/manesh/students.html\">Back to Search Page</a>\n";
print "</center>\n";
print "<br></font></body></html>\n";
}
#------------------- End of Footer ----------------------------------

#---------------- Beginning of ReadData -----------------------------
sub ReadData{
open(DatFil,"$Myfile"); ## Open the Phone Directory file
@DirData = <DatFil>; ## Read the ENTIRE file & store each line of the file as an element of the array
close DatFil;

chop(@DirData); ## Remove the last character from the array
}
#----------------- End of ReadData ----------------------------------

#----------------- Beginning of Header-------------------------------
sub Header{
print qq{
<html>
<BODY BGCOLOR="#FFFFFF">
<head><align=right>
<title> NEW JERSEY CITY UNIVERSITY </title>

</head>
<font color="#006633">
<center><h1>NEW JERSEY CITY UNIVERSITY </h1></center>
<center><h2> Campus Directory Update</h2></center>
};
}

sub my_sort{
($col,$type,@arr)=@_;

$col--;
$type="a" if $type!~ /^n$/i; ## Default Alphabetic sort

foreach(@arr){
@tmp=split(/,/,$_);
return 0 if ($col<0 || $col>(scalar @arr)); ## Invalid col no.
$new_arr=join(',',$tmp[$col],$_);
push(@new_arr,$new_arr);
}

if ($type=~ /^n$/i){ ## Numeric Sort
@new_arr=sort bynum @new_arr
}else{
@new_arr=sort byalp @new_arr
}

@arr=""; ## Re initialize the array
foreach(@new_arr){
@tmp=split(/,/,$_);
shift(@tmp); ## Remove the 1st column
$new_arr=join(',',@tmp);
push(@arr,$new_arr);
}

return @arr;
}

sub bynum{ $a <=> $b;}

sub byalp{ $a cmp $b;}
0
 

Author Comment

by:garymg44
ID: 2588305
Thank you.

Excellent!!!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

I have been pestered over the years to produce and distribute regular data extracts, and often the request have explicitly requested the data be emailed as an Excel attachement; specifically Excel, as it appears: CSV files confuse (no Red or Green h…
A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (http://www.mongodb.org/downloads),  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now