2016-09-06 108 views
0

這是我處理參數Perl的問題。我需要將perl參數參數傳遞給http請求(Webservice),無論給perl文件的參數如何。將perl文件參數傳遞給LWP HTTP請求

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

在wsgrep.pl文件中,我需要將上述參數傳遞給http post params。

像下面,

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

我使用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; 
} 

裏面我需要從給定的參數構建之後的參數部分。

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

什麼是你使用的'wsgrep.pl'? – redneb

回答

1

通常情況下,URL編碼參數,可以我會使用以下命令:

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; 
+0

哇!奇蹟般有效。謝謝你,先生! – Raja