Perl & CGI/CGI script
Expert: Justin Wheeler - 10/15/2009
QuestionI'm trying to read in name-value pairs from a POST where the value pairs are "CD=2&CD=3&CD=4
I need to be able to multiply the first value times a number and the second value times a different number, etc.
Then I need to provide the user with a total cost of items to purchase.
I seem to be having trouble figuring out how to use the 'split' properly, then do the math and then how to get it to output a page properly.
Thanks in advance for any help you may be able to provide,
Mark
AnswerHi Mark,
Your best bet is to use the CGI script, which will parse it for you.
Then, you'd do something like.
my $q = new CGI;
my @cds = $q->param( 'CD' );
print $q->header();
print "First one multiplied by six is: " . ($cd[0] * 6) . "\n";
print "Second one multiplied by five is: " . ($cd[1] * 5) . "\n";
Or even:
my $q = new CGI;
my @cds = $q->param( 'CD' );
my @multiply_by = qw( 3 7 4 2 6 9 6 43 3 67 8 );
print $q->header();
foreach my $index ( 0 .. scalar( @cds ) - 1 ) {
print "$cds[ $index ] multiplied by $multiply_by[ $index ] = " . $cds[ $index ] * $multiply_by[ $index ] . "\n";
}
If you're insistent on parsing yourself, you'll have to do something like:
my @params = map { [ split /=/, $_ ] } split( /[&;]/, $ENV{ HTTP_QUERY_STRING } );
Which would give you a data structure like:
$VAR1 = { [ CD, 1 ], [ CD, 2 ], [ CD, 3 ], .... };
Justin