BUU has asked for the wisdom of the Perl Monks concerning the following question:
Which is the default for CGI.pm and others, I want it to be parsed as follows:{ 'totallyrandom' => 'foo', 'd' => [ 'baz', 'bar', 'uno' ], 'o' => [ 'foo', 'one', 'none' ] };
I realize that these requirements are a little odd, but I feel that they happen to suit my application very well, and will be easily usable and so on. However, this requires that I write my own querystring parser which I have done, and now I present it to you in the hopes that some monk can find an error or something thats not optimal so I can fix it now before its 'in production'. It's used in the form of my $u = new QueryParse; $u->handle( $ENV{QUERY_STRING} );{ 'none' => undef, 'one' => 'uno', 'foo' => [ 'baz', 'bar' ] };
package QueryParse; use strict; sub new { return bless {}; } sub handle { my $self = shift; my $query_string = shift; if( $query_string eq '') { local $/ = undef; $query_string = <STDIN>; } #o=foo & d=baz & d=qux & o=n & d=o & d=f my @query_string = split/[;&]/,$query_string; my %arg; for( my $i = 0; $i < @query_string; $i++ ) { $_ = $query_string[ $i ]; next unless /^[oO]=/; my $o = ( split/=/ )[ 1 ]; my $j = $i + 1; my @opts; while( $j < @query_string ) { $_ = $query_string[ $j ]; last unless /^[dD]=/; my $dat = ( split/=/ )[ 1 ]; push @opts,$dat; $j++; } for( @opts ) { s / % ( [0-9A-Fa-f]{2} # match hex escapes ( %2b ) ) / chr( hex( $1 ) ) # convert in to ascii chars /xeg; # ignore whitespace, execute code, repeat } $o =~ s/%([0-9A-Fa-f]{2})/chr( hex( $1 ) )/eg; # same as above $arg{ $o } = @opts > 1 ? [ @opts ] : $opts[ 0 ]; } return %arg; } 1;
|
|---|