3

I'm getting input from an html form. There are a bunch of text inputs, thus a bunch of key-value pairs. You see my current method is excruciatingly tedious when one has more than three pairs.

I'd like to know, is there a more efficient method of turning the hash into a series of scalar variables? I want the key to be the variable name, set to the value of the key.

I'm relatively new to perl, sorry if this is a stupid question.

#!/usr/bin/perl
use strict;
use warnings;
use CGI;
use CGI qw(:standard Vars);

print "Content-type: text/html\n\n";

my %form = Vars();

$hourly = $form{hourly};
$hours_w = $form{hours_w};
$rent_m = $form{rent_m};
#...
4

4 回答 4

15

You can use a hash slice to assign to multiple variables at once:

my ($hourly, $hours_w, $rent_m) = @{$form}{qw(hourly hours_w rent_m)};

Creating variables dynamically would require eval().

于 2011-03-24T12:15:49.457 回答
5

Use CGI's OO interface.

my $q = CGI->new();
$q->import_names('Q');
print $Q::hourly; # hourly param, if any

Do not import_names into global namespace (main::) though, or you'll get in trouble sooner or later.

于 2011-03-24T13:39:26.120 回答
2

What you're trying to do is called symbolic references (see perldoc perlref and search for /Symbolic references/). It is not considered to be best practice.

Try:

for my $key ( keys %form ){
  no strict;
  $$key = $form{$key};
}
于 2011-03-24T13:17:52.370 回答
2
my $cgi;
BEGIN {
    $cgi = CGI->new();
}

BEGIN {
    # Only create variables we expect for security
    # and maintenance reasons.
    my @cgi_vars = qw( hourly hours_w rent_m );

    for (@cgi_vars) {
        no strict 'refs';
        ${$_} = $cgi->param($_);
    }

    # Declare the variables so they can be used
    # in the rest of the program with strict on.
    require vars;
    vars->import(map "\$$_", @cgi_vars);
}
于 2011-03-24T16:39:51.057 回答