Shyam
Shyam

Reputation: 149

How to get the multiple values of similar tags using Pattern Matching in Perl?

For example,

say string is "-u xyz -p 1234 -z ask -p secure -o all -p demo"

I would like to get match all the occurrences of -p and get the values of it,

I tried but it only gives stops at the first match,

$command =~ /(.*)\-p\s+(.*?)\s+(.*)/g;
print $2

which will result in

1234

Any idea, how can I recur it and get all the values: 1234, secure, demo

Upvotes: 0

Views: 106

Answers (2)

mgamba
mgamba

Reputation: 1199

This will work for the example:

$command = "-u xyz -p 1234 -z ask -p secure -o all -p demo";

while($command =~ /\-p ([^ ]+)/g) {
  print "$1\n";
}

result:

1234
secure
demo

Upvotes: 0

Andy Lester
Andy Lester

Reputation: 93725

It looks like you're trying to parse command line options. If so, use the standard Getopt::Long module that comes with Perl.

http://perldoc.perl.org/Getopt/Long.html

No need to reinvent the wheel.

Upvotes: 1

Related Questions