将 perl 文件参数传递给 LWP HTTP 请求

Pass perl file arguments to LWP HTTP request

这是我处理参数 Perl 的问题。我需要将 Perl 参数参数传递给 http 请求(Web 服务),无论给 perl 文件的参数是什么。

perl wsgrep.pl  -name=john -weight -employeeid -cardtype=physical

在 wsgrep.pl 文件中,我需要将上述参数传递给 http post 参数。

如下所示,

http://example.com/query?name=john&weight&employeeid&cardtype=physical. 

我为此 url 使用 LWP 包来获得响应。

有什么好的方法吗?

更新: wsgrep.pl

里面
my ( %args, %config );

my $ws_url =
"http://example.com/query";

my $browser  = LWP::UserAgent->new;
# Currently i have hard-coded the post param arguments. But it should dynamic based on the file arguments. 
my $response = $browser->post(
    $ws_url,
    [
        'name' => 'john',
        'cardtype'  => 'physical'
    ],
);

if ( $response->is_success ) {
    print $response->content;
}
else {
    print "Failed to query webservice";
    return 0;
}

我需要根据给定的参数构造 post 参数部分。

[
            'name' => 'john',
            'cardtype'  => 'physical'
        ],

通常,为了 url-encode 参数,我会使用以下内容:

use URI;

my $url = URI->new('http://example.com/query');
$url->query_form(%params);

say $url;

你的需求更详细。

use URI         qw( );
use URI::Escape qw( uri_escape );

my $url = URI->new('http://example.com/query');

my @escaped_args;
for (@ARGV) {
   my ($arg) = /^-(.*)/s
      or die("usage");

   push @escaped_args,
      join '=',
         map uri_escape($_),
            split /=/, $arg, 2;
}

$url->query(@escaped_args ? join('&', @escaped_args) : undef);

say $url;