Search code examples
perlcgi

how to get POST values in perl


I am trying to customize a script and need to get a POST value from a form using perl. I have no background of perl but this is a fairly simple thing so I guess it should not be hard.

This is the php version of the code I would like to have in PERL:

<?php
$download = ($_POST['dl']) ? '1' : '0';
?>

I know this may not be at all related to the PERL version but it could help I guess clarifying what exactly I am looking to do.


Solution

  • Well, in that case please have a look at this simple code: This would help you:

    #!/usr/bin/perl
    use strict;
    use warnings;
    use CGI;
    use CGI::Carp qw(fatalsToBrowser);
    
    sub output_top($);
    sub output_end($);
    sub display_results($);
    sub output_form($);
    
    my $q = new CGI;
    
    print $q->header();
    
    # Output stylesheet, heading etc
    output_top($q);
    
    if ($q->param()) {
        # Parameters are defined, therefore the form has been submitted
        display_results($q);
    } else {
        # We're here for the first time, display the form
        output_form($q);
    }
    
    # Output footer and end html
    output_end($q);
    
    exit 0;
    
    # Outputs the start html tag, stylesheet and heading
    sub output_top($) {
        my ($q) = @_;
        print $q->start_html(
            -title => 'A Questionaire',
            -bgcolor => 'white');
    }
    
    # Outputs a footer line and end html tags
    sub output_end($) {
        my ($q) = @_;
        print $q->div("My Web Form");
        print $q->end_html;
    }
    
    # Displays the results of the form
    sub display_results($) {
        my ($q) = @_;
    
        my $username = $q->param('user_name');
    }
    
    # Outputs a web form
    sub output_form($) {
        my ($q) = @_;
        print $q->start_form(
            -name => 'main',
            -method => 'POST',
        );
    
        print $q->start_table;
        print $q->Tr(
          $q->td('Name:'),
          $q->td(
            $q->textfield(-name => "user_name", -size => 50)
          )
        );
    
        print $q->Tr(
          $q->td($q->submit(-value => 'Submit')),
          $q->td('&nbsp;')
        );
        print $q->end_table;
        print $q->end_form;
    }