Perl Subtitle Doesn't Work After Previous Pattern Matching

I have a strange problem that the susbtitute s/// operator does not work after matching the previous pattern. for instance

 use strict; use warnings; my $var = "var"; $var =~ s||/|g; print "$var\n"; 

Output: /v/a/r/

But in this case

 use strict; use warnings; my $a = "test"; if ($a =~ /te/) { my $var = "var"; $var =~ s||/|g; print "$var\n"; } 

output: var when it should match the previous result.

What's going on here? How can i fix this?

+6
source share
1 answer

perlop talks about an empty template //

If PATTERN evaluates to an empty string, the last successfully matched regular expression is used instead. In this case, only the g and c flags on the empty template are respected; other flags are taken from the original drawing. If the match has not been previously done, it will (silently) act as a genuine empty template (which will always match).

So, your first case makes a replacement on an empty line, because there were no matches of the previous patterns, and the second after a successful match of te in test , so it replaces te everywhere in var and therefore has no effect.

This program demonstrates

 use strict; use warnings; my $str = 'a/b/c'; if ($str =~ m{/}) { $str =~ s//x/g; } print $str; 

Output

 axbxc 

The only exception to this is the template in the split command, which always matches empty templates if that is what you specify.

To get around this, if you really want to match the dot before and after each character, you can use the /x modifier to use a small space for your pattern, for example

 use strict; use warnings; my $var_a = 'test'; if ($var_a =~ /te/) { my $var_b = 'var'; $var_b =~ s| |/|gx; print "$var_b\n"; } 

Output

 /v/a/r/ 
+5
source

Source: https://habr.com/ru/post/973896/


All Articles