[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 474
  • Last Modified:

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>
0
Nicholas Niggel
Asked:
Nicholas Niggel
  • 7
  • 6
1 Solution
 
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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
 
Nicholas NiggelAuthor Commented:
kandura That's what I needed.

Thanks for all the Help.

0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

  • 7
  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now