Perl has two separate, but largely compatible variable systems. Global variables that are in the symbol table, and lexical variables that are associated with lexical areas in the field.
Global variables can be subject to symbolic dereferencing and are subject to dynamic scope with local . Lexical variables (defined with my ) can be closed.
Regular expression matching variables (and all other Perl special variables) are global variables in the symbol table, so there is no way to close them.
To fix this, simply copy the value to the lexical:
use warnings; while ("1234567890"=~/(.)/sg) { my $x = $1;
source share