According to perlvar :
Regular Expression Variables
These variables are read-only and dynamic in scope, unless we note otherwise. The dynamic nature of the regular expression variables means that their value is limited to the block in which they are located.
and further down:
Traditionally, in Perl, any use of any of the three variables $`, $&or $'anywhere in the code caused by all subsequent successful patterns match to make a copy of the consistent string, in case the code can subsequently access one of these variables.
After reading the rest of the section from the documentation, I still missed some information, for example:
Why is the copy made in the first place?
I think I know the answer to this question: it is somehow clear from the last statement "in case the code might subsequently access one of those variables". So, in my understanding:
my $s = "Hello world";
$s =~ s/Hello //;
say $';
it will still print world, since a copy was made before it was modified $s.
Why is a copy of the whole line running?
In the previous example, it would be enough to copy only the final part of the string, since it was used only $'(we did not use $`or $&). So why copy the entire line?
Finally: as he says "all subsequent", and not "all subsequent matches in that block", I would like this to be confirmed:
my $s = "no\n yesHello world";
{
$s =~ /yes/ and say $';
}
$s = '12' x 1_000_000;
my $n = () = $s =~ /2/g;
say "Found $n matches";
( $' ), , $s =~ /2/g? (Asumming $`, $& $' )