Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I want to update this part of a script on Unix OS where it is using the pack to decode data entry and instead use the CGI module to do it

Here is the current part:
use strict; sub parse_form { # Get the input read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); # Split the name-value pairs my @pairs = split(/&/, $buffer); my $name; my $value; foreach my $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; $FORM{$name} = $value; } }
My attempt using the CGI param method hopefully to bring this script up to date using the CGI module:
use strict; use CGI qw(:standard); sub parse_form { # Get the input read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); # Split the name-value pairs my @pairs = split(/&/, $buffer); my $name; my $value; foreach my $pair (@pairs) { foreach my $stuff (param($pair)) { ($name, $value) = split(/=/, $stuff); $FORM{$name} = $value; } }
Please advise what I am doing wrong because it doesnt want to work?

Replies are listed 'Best First'.
Re: Using CGI param method
by sgifford (Prior) on Apr 20, 2004 at 16:55 UTC
    CGI will have already read the input. You should simply use something like:
    #!/usr/bin/perl -Tw use strict; use CGI; our $q = CGI->new(); our %FORM; sub parse_form { # Get the input foreach my $p ($q->param()) { $FORM{$p}=$q->param($p); } } parse_form(); print "Content-type: text/plain\n\n"; while(my($k,$v)=each(%FORM)) { print "$k: $v\n"; }

    Updated: Fix error (shouldn't use both :standard and create a CGI object) and add enough code to make this a complete, testable program.

      Is there a particular reason to use: use CGI? qw(:standard); and then create the CGI object? By creating the CGI object you already have access to all the methods normally exported by :standard. Is there something I'm missing here?

      The only explanation I can guess at would be a mod_perl situation where you wanted to preload as much of the CGI module as possible before the webserver forked.

      Thank you for any insight you can provide.

        No, I just cut-n-pasted the OP's code and forgot to remove that. For mod_perl you'd use the -compile pragma to preload and pre-compile.

      It's even easier than that! CGI's Vars returns the very hash you're looking for.

      #!/usr/bin/perl -wT use strict; use CGI qw( header Vars ); my %FORM = Vars(); ### Bingo! print header( 'text/plain' ); $\ = "\r\n"; use Data::Dumper; print Dumper(\%FORM);
      Thanks I tried just exactly as you suggested and it doesnt work. Please advise if there is anything I can do to make this work?
        It works for me, so you'll need to post a bit more information about what you're doing, what you expect to happen, and what's happening instead.