Caveats apply. This is not recursive and it almost certainly should be; it fails on deeper data structures. It only serializes. I am almost positive there is something in some corner of the CPAN that does this but I couldn't find it in a somewhat casual search. This is first draft quality code. This style of query string is popular with PHP and Ruby apps. I think this is how jQuery does it if you don't request "traditional" (meaning *standards compliant* serialization) so it might be good to just copy its code if there turns out to be nothing solid in Perl already.
use strictures;
use Carp;
use URI::Escape;
my %hash = ( "name" => "test name",
"file_ids" => [ 1, 2 ],
"sub" => { "name" => "foo",
"message" => "bar" } );
print serialize_web2_0_query_string(\%hash), $/;
sub serialize_web2_0_query_string {
no warnings "uninitialized";
my $datum = shift;
my $strings = shift || [];
for my $key ( keys %$datum )
{
if ( ref $datum->{$key} eq "HASH" )
{
while ( my ( $k, $v ) = each %{ $datum->{$key} } )
{
push @$strings, sprintf "%s[%s]=%s", uri_escape($key),
+ uri_escape($k), uri_escape($v);
}
}
elsif ( ref $datum->{$key} eq "ARRAY" )
{
push @$strings, sprintf "%s[]=%s", uri_escape($key), uri_e
+scape($_) for @{ $datum->{$key} };
}
elsif ( not ref $datum->{$key} )
{
push @$strings, join "=", map uri_escape($_), $key, $datum
+->{$key};
}
else
{
croak "Nope. Don't know what to do with ", $key, " => ", $
+datum->{$key};
}
}
return join "&", @$strings
}
__DATA__
sub[name]=foo&sub[message]=bar&file_ids[]=1&file_ids[]=2&name=test%20n
+ame