Balakumar
Balakumar

Reputation: 650

Capture the match content of two different regexp in perl

I am using a while loop with two separate regular expression

while(($string1=~m/(\d+)/igs)==($string2=~m/([^^]*?)\n+/igs)) {}

to store the value of the matching pattern of the $string1 i have used $temp1=$1,

How can I store the matching pattern of the $string2. Please give some suggestion.

Upvotes: 7

Views: 656

Answers (3)

mpapec
mpapec

Reputation: 50637

my ($m1,$m2);
while (do{
  ($m1,$m2) = ();
  $m1 = $1 if $string1 =~ /(\d+)/igs;
  $m2 = $1 if $string2 =~ /([^^]*?)\n+/igs;
  defined $m1 == defined $m2;
}) {
  # print "$m1-$m2-\n";
}

Upvotes: 5

VolDeNuit
VolDeNuit

Reputation: 53

If the "g" and "s" options aren't really necessary to your task and you actually only want to compare the first matching substrings, you can make a one-line test as follows:

if (($a =~ /regex1/)[0] == ($b =~ regex2/)[0]) {
    ...

And if you need to know what the two matched strings were, just add some temporary variables to hold them:

if (($first = ($a =~ /regex1/)[0]) == ($second = ($b =~ regex2/)[0])) {
    ...

But if you really want to compare all of the successive matches in each string to see if each pair are equal, there's no single-statement solution I can think of that will do it. Your regexes each return a list and "==" only compares their lengths. You've got to use the first solution proposed above and write out the comparison code in "long-hand".

The second solution above won't work since it will keep testing only the first match in each string.

It's a bit hard to understand what you're trying to do but you could at least drop the "i" option on the first test for /(\d+)/. Presumably the "s" option is only needed for the second string since you're looking for embedded new-lines.

Upvotes: 0

Barmar
Barmar

Reputation: 781004

There might be more clever ways, but I'd just break them up into separate statements:

while (1) {
    $res1 = $string1=~m/(\d+)/igs;
    $temp1 = $1;
    $res2 = $string2=~m/([^^]*?)\n+/igs
    $temp2 = $1;
    last unless $res1 == $res2;
    ...
}

Just because it's perl you don't have to find the most terse, cryptic way to write something (that's what APL is for).

Upvotes: 3

Related Questions