perlperl-hash

How to turn a perl hash of an html form into a series of scalar variables?


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};
#...

Solution

  • 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);
    }