Perl - How can I turn a hash into a query string?

2019-07-20 16:06发布

问题:

How can I turn a hash into a query string? I would like to find a solution that doesn't involve using the CGI module. Here's an example of what I'm wanting to do but don't know what the best and most elegant approach would be, since I'm relatively new to Perl.

Hash:

my $data = {
         'key1' => 'value1',
         'key2' => 'value2',
         'key3' => 'value3',
         'key4' => 'value4'
};

To desired query string:

key1=value1&key2=value2&key3=value3&key4=value4

回答1:

use URI qw( );
my $url = URI->new('', 'http');
$url->query_form(%$data);
my $query = $url->query;

If you're actually trying to build a POST request, check out HTTP::Request::Common's POST.



标签: perl hash