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
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/
source share