Phoenix.pm: Parameter parser

phaedrus at illogics.org phaedrus at illogics.org
Tue Nov 26 14:38:54 CST 2002


Theres no one here but us endangered bobtailed lesser plumed plum crested
symbol owls!

My solution, in two lines:

# test data
$_ = qq{param1 param2="value2" param3="value3 \\"foo\\""};

s{(\w+)\s*=?\s*(['"]?)(.*?)(?<!\\)\2}{$hash{$1} = $3;''}ge;
foreach my $i (keys %hash) { $hash{$i} =~s/\\//g }

# output results
foreach my $i (keys %hash) { print $i, ' = ', $hash{$i}, "\n"; }

# end perl

This should handle qouting with ' or ".
I'm sure there is a one line solution as well.

Thats somewhat similar to something I just did (this seems to happen
a lot in Perl-land).

I decided that CGI was entirely too large at 6695 lines, so I
decided to rewrite it, or atleast the parts of it that I actually use:

my $in = $ENV{QUERY_STRING}||''; $in.='&'; read(STDIN, $in, $ENV{CONTENT_LENGTH}||0, length($in));
map { $nam='word';s{^([a-z]+)=}{$nam=$1;''}e; tr/+/ /; s/%(..)/pack('c',hex($1))/ge; $$nam=$_; } split/[&;]/, $in;

This decodes GET and/or POST data.

I personally feel that something that can't be done in one line isn't
feel enough understood, or else it could be paired down to its essential core.

I'm reading in $ENV{QUERY_STRING} or else the empty string (to make warn happy),
concat'ing the '&' seperator, then reading from STDIN for whatever length 
$ENV{CONTENT_LENGTH} specifies starting at the end of what we read from the
query string. This way, GET variables have priority over POST variables.
I split that on ";" or "&", and do a few string operations (all of which
default to $_) on $_. First, replace a varname composed of lowercase letters
with '', stashing that in $nam over top of the default 'word'. Then I
decode what is left, using a symbol table lookup to store in the variable
specified by $nam. 

Oh?? And who makes you code Perl? Would it be, hmm, SATAN!?

-scott

> Hey all,
> 
> I just implemented a parser that takes something like this:
> 
> command param1 param2="value2" param3="value3 \"foo\""
> 
> and puts the parameters and values into a hash.  The value for param1 
> would be "1".  I'm not sure I implemented it the best way, though.  I 
> thought I'd get some ideas from you folks to get a different 
> perspective.  I'll post what I did after I get some responses.  I don't 
> want to contaminate your thinking. :)
> 
> 




More information about the Phoenix-pm mailing list