Question

I'm trying for substitution in which a condition will allow or disallow substitution. I have a string

$string = "There is <tag1>you can do for it. that dosen't mean <tag2>you are fool.There <tag3>you got it.";

Here are two hashes which are used to check condition.

my %tag = ('tag1' => '<you>', 'tag2'=>'<do>', 'tag3'=>'<no>');
my %data = ('you'=>'<you>');

Here is actual substitution in which substitution is allowed for hash tag values not matched.

$string =~ s{(?<=<(.*?)>)(you)}{
    if($tag{"$1"} eq $data{"$2"}){next;}
    "I"
}sixe;

in this code I want to substitute 'you' with something with the condition that it is not equal to the hash value given in tag.
Can I use next in substitution? Problem is that I can't use \g modifier. And after using next I cant go for next substitution. Also I can't modify expression while matching and using next it dosen't go for second match, it stops there.

Was it helpful?

Solution 2

It was simple but got my two days to think about it. I just written another substitution where it ignores previous tag which is cancelled by next;

$string = "There is <tag1>you can do for it. that dosen't mean <tag2>you are fool.There <tag3>you got it.";


my %tag = ('tag1' => '<you>', 'tag2'=>'<do>', 'tag3'=>'<no>');
my %data = ('you'=>'<you>');

my $notag;

$string =~ s{(?<=<(.*?)>)(you)}{
    $notag = $2;
    if($tag{"$1"} eq $data{"$2"}){next;}
    "I"
}sie;

$string =~ s{(?<=<(.*?)>)(?<!$notag)(you)}{
   "I"
}sie;

OTHER TIPS

You can't use a variable length look behind assertion. The only one that is allowed is the special \K marker.

With that in mind, one way to perform this test is the following:

use strict;
use warnings;

while (my $string = <DATA>) {
    $string =~ s{<([^>]*)>\K(?!\1)\w+}{I}s;
    print $string;
}

__DATA__
There is <you>you can do for it. that dosen't mean <notyou>you are fool.
There is <you>you can do for it. that dosen't mean <do>you are fool.There <no>you got it.

Output:

There is <you>you can do for it. that dosen't mean <notyou>I are fool.
There is <you>you can do for it. that dosen't mean <do>I are fool.There <no>you got it.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top