Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I've been racking my brain about this code for days. It takes the user's input (a name or part of a name), checks to see if it has only one word, then it should use a grep function to find the person's answer in the array that contains the file. But it doesn't even print out anything. When I stopped using grep and used a "foreach" loop to put it inot a variable, then using an "if" loop to first check the line for the word, and pushing it into array, it just displays the whole file.
#!/usr/bin/perl #Start the modules use strict; use CGI; #Create a new CGI object my $Page = new CGI; #Take the inoformation from the CGI module my $Info = $Page->param("words"); #Print out an HTML MIME Header print $Page->header; #Print out the proper HTML print <<HTMLSTUFF; <html> <head> <title> Your results </title> <style language="text/css"> <!-- p { font-family: Arial, Times New Roman, Garamond; } //--> </style> </head> <body bgcolor="lightGreen"> HTMLSTUFF #Check to see if the information has only one word if ($Info =~ m/ /) { print "<p>Please use only one word.</p>\n"; print <<MOREHTML; </body> </html> MOREHTML exit; } #Make sure the file can be opened unless (open (FILE, "<../Names.html")) { print "<p>Make sure the file is there</p>\n"; print <<MOREHTML; </body> </html> MOREHTML exit; } #Read the whole thing into an array my @Lines = <FILE>; #Close the file close (FILE); #Use "grep" to find the goods my @Names =~ grep("$Info", @Lines); my $i; ############The whole thing #Print out the word "Results print "<p>Here's the results</p>\n"; #Print out all of that shit #Do a "for" loop to print each of the names for ($i=0; $i<=@Names; $i++) { print "<p>$Names[$i]</p>\n"; } ##########End it all print "</body>\n"; print "</html>\n";
Please Perl Monks, you are my only hope...

Replies are listed 'Best First'.
Re: Looking through a file...
by BeernuT (Pilgrim) on Mar 31, 2002 at 06:03 UTC
    instead of
    my @Names =~ grep("$Info", @Lines);
    try
    my @Names = grep(/$Info/, @Lines);
    or even better
    my @Names = grep(/^$Info$/, @Lines);
    also adding
    use warnings; or #!/usr/bin/perl -w (pre 5.6)
    should have let you known that something was wrong.
    let me know if this helps

    -bn
Re: Looking through a file...
by zengargoyle (Deacon) on Mar 31, 2002 at 06:33 UTC

    Try something like this:

    # blah blah blah ... print $Page->header; print <<HTMLSTUFF; <body> HTMLSTUFF do_work($Info); print <<HTMLSTUFF; </body> HTMLSTUFF exit; sub do_work { my $Info = shift; print "<p>matching: $Info</p>$/"; if ( $Info =~ / / ) { print "<p>one word only please</p>\n"; return; } unless (open (FILE, "<names.html")) { print "<p>open: $!</p>\n"; return; } my @Names = grep(/$Info/,<FILE>); foreach my $Name (@Names) { print "<p>$Name</p>\n"; } close(FILE); }

    Can 'ya tell I don't do much CGI.. :(