9

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

From this link:

http://www.someaddress.com/index.html?test=value&code=INT_12345

It can be done using URI::URL or URI (I know the first one is kind of obsolete). Thanks in advance.

1

2 Answers 2

11

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");
Sign up to request clarification or add additional context in comments.

Comments

8
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.