如何在perl中获取POST值

Aho*_*tbi 7 perl cgi

我正在尝试自定义脚本,需要使用perl从表单中获取POST值.我没有perl的背景,但这是一个相当简单的事情,所以我想它应该不难.

这是我希望在PERL中拥有的代码的php版本:

<?php
$download = ($_POST['dl']) ? '1' : '0';
?>
Run Code Online (Sandbox Code Playgroud)

我知道这可能与PERL版本无关,但它可以帮助我猜清楚我到底要做什么.

vij*_*jay 7

那么,在这种情况下,请看一下这个简单的代码:这可以帮助你:

#!/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;
}
Run Code Online (Sandbox Code Playgroud)


dax*_*xim 5

风格建议:您几乎不需要为变量赋值 0 或 1。只需在 bool 上下文中评估值本身。


CGI.pm (CGI) 中,该param方法合并了 POST 和 GET 参数,因此我们需要单独检查请求方法:

#!/usr/bin/env perl
use strict;
use warnings FATAL => 'all';
use CGI qw();
my $c = CGI->new;
print $c->header('text/plain');
if ('POST' eq $c->request_method && $c->param('dl')) {
    # yes, parameter exists
} else {
    # no
}
print 'Do not taunt happy fun CGI.';
Run Code Online (Sandbox Code Playgroud)

使用Plack::Request (PSGI),除了混合接口 ( )之外,您还有不同的 POST ( body_parameters) 和 GET ( query_parameters)方法parameters

#!/usr/bin/env plackup
use strict;
use warnings FATAL => 'all';
use Plack::Request qw();
my $app = sub {
    my ($env) = @_;
    my $req = Plack::Request->new($env);
    if ($req->body_parameters->get_all('dl')) {
        # yes
    } else {
        # no
    }
    return [200, [Content_Type => 'text/plain'], ['Do not taunt happy fun Plack.']];
};
Run Code Online (Sandbox Code Playgroud)