Perl - Parse URL to get a GET Parameter Value

前端 未结 2 1807
情深已故
情深已故 2020-12-20 17:43

How to get the value of a parameter code using URI::URL Perl module?

From this link:

http://www.someaddress.com/inde

相关标签:
2条回答
  • 2020-12-20 17:45

    Create a URI object and use the query_form method to get the key/value pairs for the query. If you know that the code parameter is only specified once, you can do it like this:

    my $uri   = URI->new("http://www.someaddress.com/index.html?test=value&code=INT_12345");
    my %query = $uri->query_form;
    
    print $query{code};
    

    Alternatively you can use URI::QueryParam whichs adds soem aditional methods to the URI object:

    my $uri = URI->new("http://www.someaddress.com/index.html?test=value&code=INT_12345");
    print $uri->query_param("code");
    
    0 讨论(0)
  • 2020-12-20 18:00
    use URI;
    my $uri   = URI->new("http://someaddr.com/index.html?test=FIRST&test=SECOND&code=INT_12345");
    my %query = $uri->query_form;
    use Data::Dumper;
    print Dumper \%query;
    

    We can see:

       $VAR1 = {
                  'test' => 'SECOND',
                  'code' => 'INT_12345'
                };
    

    Unfortunately, this result is wrong.

    There is possible solution:

    use URI::Escape;
    
    sub parse_query {
       my ( $query, $params ) = @_;
       $params ||= {};
       foreach $var ( split( /&/, $query ) ){
         my ( $k, $v ) = split( /=/, $var );
         $k = uri_unescape $k;
         $v = uri_unescape $v;
         if( exists $params->{$k} ) {
            if( 'ARRAY' eq ref $params->{$k} ) {
               push @{ $params->{$k} }, $v;
            } else {
               $params->{$k} = [ $params->{$k}, $v ];
            }
         } else {
            $params->{$k} = $v;
         }
       }
       return $params;
    }
    
    0 讨论(0)
提交回复
热议问题