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

I know this will be answered very quickly, but I haven't used perl in a ong time and I can't seem to find any books around me. I have an html driver page with a form on it which sends the variables on the form to a cgi-page. All I want to do is to tell my cgi page to get the variables and print them to a file seperated by colons or something. Could someone tell me the best method of doing this.(I know you guys didn't even have to think on this one :-)

Thanks

Edit 2001-06-02 by mirod: changed title

  • Comment on Printing variables from CGI form (was: I know this is very easy)

Replies are listed 'Best First'.
(jeffa) Re: I know this is very easy
by jeffa (Bishop) on Jun 02, 2001 at 01:56 UTC
    Use CGI.pm!!
    use strict; use CGI; my $CGI = new CGI; print $CGI->header, $CGI->start_html, $CGI->pre; foreach my $name ($CGI->param) { print "$name = ", $CGI->param($name), "\n"; }

    UPDATE: (an explanation)

    When a form is submitted to a Perl script that uses CGI.pm, the form variables are magically available via the param() method.

    The param() method works two ways: when called with no args, it returns a list of the available form variables. When called with a single argument(the name of the form variable you want the value of) it returns the value of that variable.

    The big gotcha is dealing with multiple-valued variables, then param() will return a list of the values. Change the line inside the for loop to this:

    my $value = join(",", $CGI->param($name)) || ''; print "$name = $value\n";
    if you want to handle multiple-valued variables. Otherwise the script will only print the last assigned value. Jeff

    R-R-R--R-R-R--R-R-R--R-R-R--R-R-R--
    L-L--L-L--L-L--L-L--L-L--L-L--L-L--
    
      ...and for Old and New alike, the functional interface to CGI.pm is much cleaner and easier to understand. The following is functionally (:-D) identical to jeffa's code:
      use strict; use CGI qw(:standard); print header, start_html, pre; foreach my $name (param) { print "$name = ", param($name), "\n"; }
      Less typing means a few more months before Carpal Tunnel sets in.

      Gary Blackburn
      Trained Killer

      If you don't mind "polluting" your name space, CGI.pm can also magically create a hash of your parameters with the Vars method.
      my %params=$cgi->Vars;
Re: I know this is very easy
by Zaxo (Archbishop) on Jun 02, 2001 at 08:35 UTC

    For OO CGI.pm the save() method is convenient. If you use the function interface save_parameters() is the call.

    #!/usr/bin/perl -wT # -*-Perl-*- use strict; use CGI; my $cgi = new CGI; open QFILE, ">> ./data/victims.txt"; $cgi->save(QFILE); close(QFILE);

    After Compline,
    Zaxo