cgi upload file and count words

Hello
I am a student working on homework. Prob is get a file with cgi from html page, upload file and count words, display results. I'm sure its a common hw prob but I am stuck. Also, have checkbox to upload automatically a file for testing "raven.txt" if checked

Any help much appreciated, please explain my mistake.
cgi is below also html below that

!/usr/bin/perl
#file: upload.pl

use CGI qw/:standard/;

print header,
    start_html('Word Counter'),
    h1('Word Counter');

print_form()    unless param;
print_results() if param;
print end_html;

sub print_form {
    print start_multipart_form(),
       filefield(-name=>'upload',-size=>60),br,
       submit(-label=>'Upload File'),
       end_form;
}

sub print_results {
    my $length;
    my $file = param('upload');
    if (!$file) {
        print "No file uploaded.";
        return;
    }
    print h2("File name\n"),$file;
    my $lines = 0;
    my $words = 0;
    my @words;
    my @output;
    @lines = @_;
    foreach (@lines){
            $lines++;
             @words = split;
             foreach(@words){
                     $words++;
             }
    }
    print "<br><b>Number of Lines:</b> $lines <br>\n";
    print "<b>Number of Words:</b> $words <br>\n";

}

#     html  

<html>
<title>Basic Word Counter</title>
<body>
<h1>Word Counting Program</h1>
What file would you like to process
<form action="/cgi-bin/word.cgi" method="post" enctype="multipart/form-data">
File Name:
<br>
<input type="file" name="upload" size="40">
<br>
<br>
<input type="reset" label="RESET">
<input type="submit" name=".submit" value="Count Words">
<input type="hidden" name=".cgifields" value="raven">
<br><br>
<input type="checkbox" name="raven" value="on">
Or choose
<a href="raven.txt">The Raven</a>
</form>
</body>
</html>
Nicholas NiggelAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

kanduraCommented:
Where do you get your lines from? And where did you _expect_ them to come from?
Once you find the difference between those two, you will have your answer :-)

Kandura
0
Nicholas NiggelAuthor Commented:
OK while you where answering I did this with $ARGV it now counts choosen file
What about the checkbox for auto uploading?

#!/usr/bin/perl
#file: upload.pl

use CGI qw/:standard/;

print header,
    start_html('Word Counter'),
    h1('Word Counter');

print_form()    unless param;
print_results() if param;
print end_html;

sub print_form {
    print start_multipart_form(),
       filefield(-name=>'upload',-size=>60),br,
       submit(-label=>'Upload File'),
       end_form;
}

sub print_results {
    my $length;
    my $file = param('upload');
        if (!$file) {
      $file="raven.txt";
      open(FILE, "$file") || die "Cannt: $!\n";
      while (<FILE>) {
        $lines{$ARGV}++;
        @words = split(/\W+/);
        $count{ARGV} += @words;
      }
      foreach $linecount (sort keys %lines) {
          print h2('File Lines'), $lines{$linecount};
      }
      foreach $wordcount (sort keys %count) {
          print h2('File Words'), $count{$wordcount};
      }
    }
    else {
         while (<$file>) {
           $lines{$ARGV}++;
           @words = split(/\W+/);
           $count{$ARGV} += @words;
        }
        foreach $linecount2 (sort keys %lines) {
            print h2('File Lines'), $lines{$linecount2};
        }
        foreach $wordcount2 (sort keys %count) {
            print h2('File Word'), $count{$wordcount2};
        }
    }
       
}

0
kanduraCommented:
very good :-)

yes, how about that checkbox...
You have to add it to your form of course, so the user can see it, and check it if they want.
Then you will have to check if it has been selected, and act accordingly.
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Nicholas NiggelAuthor Commented:
kandura - you still out there ? Or anyone else ?
Can you take a look at this and give me a pointer as to why my print_raven doesn't count words or lines ?


#!/usr/bin/perl

use CGI ':standard';
use CGI::Carp 'fatalsToBrowser';

print_form() unless param;
print_results() if param ('upload');
print_raven() if param ('The Raven');
print end_html;

sub print_form {
     print header;
     print start_html(-title=>'Basic Word Counter');
     print h1("Basic Word Counter");
     print start_multipart_form();
     print "Please upload a file";
     print br;
     print filefield(-name=>'upload', -size=>40);
     print br;
     print checkbox(-name=>'The Raven');
     print br;
     print br;
     print submit(-label=>'GO');
     print reset;
     print endform;
}

sub print_results {  
    my $file = param('upload');
    print header;
    print start_html;
    print h1("The file you selected has:");
    print br;
    while (<$file>) {  
       $lines{$ARGV}++;
       @words = split(/\W+/);
       $count{$ARGV} += @words;
    }
    foreach $linecount2 (sort keys %lines) {
        print h2('File Lines'), $lines{$linecount2};
    }
    foreach $wordcount2 (sort keys %count) {
        print h2('File Word'), $count{$wordcount2};
    }
   print h2('File Name'), $file;
}    

sub print_raven {
    my $file = 'raven.txt' ;
    print header;    
    print start_html;
    print h1("The Raven has:");
    print br;
    while (<$file>) {
       $lines++;
       @words = split(/\W+/);
       $count += @words;
    }
    foreach $linecount2 (sort keys %lines) {
        print h2('File Lines'), $lines{$linecount2};
    }
    foreach $wordcount2 (sort keys %count) {
        print h2('File Word'), $count{$wordcount2};
    }
   print h2('File Name'), $file;
}
0
kanduraCommented:
That's because you do not have the hashes %lines or %count.
The number of lines is in $lines and the word count is in $count.

So remove the two foreach blocks from print_raven and add instead:

   print h2('File Lines'), $lines;
   print h2('File Word'), $count;
0
Nicholas NiggelAuthor Commented:
Thanks for getting back to me.
I see my use of the hashes instead of scaler(thanks for pointing that out), but I tried your suggestion and it still doesn't show a number count for words and lines.
Is this correct:

   while (<$file>) {
       $lines++;
       @words = split(/\W+/);
       $count += @words;
    }
I have the file raven.txt in the same directory.
0
kanduraCommented:
Yes, that looks about ok. However, there may be a problem opening the file. Make sure that the webserver user has permission to read it.

Try opening it explicitly to see if that's the problem:

sub print_raven {
    my $file = 'raven.txt' ;
    print header;    
    print start_html;
    print h1("The Raven has:");
    print br;
    open F, "$file" or print "<b>Error opening $file: $!</b><br>";      # <---- this might give you a clue
    while (<F>) {
       $lines++;
       @words = split(/\W+/);
       $count += @words;
    }
    close F;
 
   print h2('File Lines'), $lines;
   print h2('File Word'), $count;
   print h2('File Name'), $file;
}
0
Nicholas NiggelAuthor Commented:
Well that did the trick. It works with that.
must have been this

open F, "$file"

I was trying to read the file without opening it. Do I need to open it with an open statement first ?
0
Nicholas NiggelAuthor Commented:
How about this.
WHen I hit the GO button without selecting a file and without checking the checkbox. I get an error

Error message:
Premature end of script headers: word.cgi

it should just call the print_form() routine from this
print_form() unless param;

Any ideas ?
0
kanduraCommented:
About opening: yes, in this case you should. The upload field gives you an already opened filehandle to the uploaded file.

About form: I think the submit button also sends a parameter (usually its name). The best thing you can do is check if the form was posted.
If it wasn't, chances are that $ENV{'REQUEST_METHOD'} eq 'GET', while it will definitely be 'POST' when the form was submitted.
Otherwise, check on the explicit parameters you need.
0
Nicholas NiggelAuthor Commented:
The form is a post. Would I check this in the cgi by looking for a param ? like

print_form() if param ('GO');
I tried that and no good.

I thought that
print_form()    unless param;  
would do it
0
kanduraCommented:
   print_form()    unless param;
will work; it will print the form when the script is requested without any parameters.

However, if soneone submits the form without setting a filename or checking the 'raven' box,
then your script will do this:

print_form() unless param;                # skipped because of .submit param (from the submit button)
print_results() if param ('upload');       # skipped because no file selected
print_raven() if param ('The Raven');   # skipped because not checked
print end_html;

So you're missing the HTTP header and the start_html in this case.

I suggest you move the
    print header;    
    print start_html;
from every subroutine, and add it at the top of your script:

    print header;    
    print start_html;
   
    print_form() unless ( param('upload') or param('The Raven') );   # <------ note that now we print the form if nothing was filled in
    print_results() if param ('upload');
    print_raven() if param ('The Raven');
    print end_html;
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Nicholas NiggelAuthor Commented:
kandura That's what I needed.

Thanks for all the Help.

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Perl

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.