Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl - Parse URL to get a GET Parameter Value

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.

like image 305
user1246172 Avatar asked Sep 14 '12 13:09

user1246172


2 Answers

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");
like image 134
pmakholm Avatar answered Sep 22 '22 04:09

pmakholm


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;
}
like image 21
oklas Avatar answered Sep 24 '22 04:09

oklas