0

I have a string as below:

$var = "ABC/type.xml/BYB?not=1234&at=6789&xyz&LMN";

I want to get the not and at values.. How can work with it??

user2013387
  • 203
  • 1
  • 3
  • 8
  • What have you researched or tried? – HamZa Apr 21 '14 at 22:40
  • I have tried to split the variable using '?' first which gives us a variable with var2 ="not=1234&at=6789&xyz&LMN" – user2013387 Apr 21 '14 at 22:50
  • Then I am splitting using & . It increases my lines of code.. is there any other way?? – user2013387 Apr 21 '14 at 22:51
  • I'm no expert, but i found this: [http://stackoverflow.com/questions/7363899/how-to-extract-values-from-a-string-in-javascript][1] [1]: http://stackoverflow.com/questions/7363899/how-to-extract-values-from-a-string-in-javascript – Benjaroo Apr 21 '14 at 23:08
  • http://stackoverflow.com/a/18355942/725418 – TLP Apr 21 '14 at 23:14

3 Answers3

5

You can, and probably should, use a proper module that can parse this string properly, such as URI and URI::QueryParam:

use strict;
use warnings;
use URI;
use URI::QueryParam;

my $str = "ABC/type.xml/BYB?not=1234&at=6789&xyz&LMN";
my $url = URI->new($str);
my $not = $url->query_param('not');
my $at  = $url->query_param('at');
print Dumper $not, $at;

Output:

$VAR1 = '1234';
$VAR2 = '6789';
TLP
  • 66,756
  • 10
  • 92
  • 149
2

The easiest thing is probably to pull all the values out into a hash in a single shot:

my $var = "ABC/type.xml/BYB?not=1234&at=6789&xyz&LMN";

my %values = $var =~ /(\w+)(?:=(.*?))?(?:&|\Z)/g;

After this, you have

  DB<5> x \%values
0  HASH(0x7fa133018f98)
   'LMN' => undef
   'at' => 6789
   'not' => 1234
   'xyz' => undef
Mark Nodine
  • 163
  • 7
0

You could try using regex to extract the matches:

my $var = "ABC/type.xml/BYB?not=1234&at=6789&xyz&LMN";

$var=~/not=(.*?)&/;
my $a=$1;
$var=~/at=(.*?)&/;
my $b=$1;

say $a,",",$b;

Output:

1234,6789
Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174