Cannot use "my $_" in new version(s) of Perl

Viewed 554

In Perl 5.28.1, the following statement is invalid:

>perl
my $_;

Can't use global $_ in "my" at - line 1, near "my $_"
Execution of - aborted due to compilation errors.

This worked at least up to Perl 5.16.3. Was this construct removed from Perl, or is this a bug? If this was removed, I consider that a big problem as this basic construct has been heavily used in the past, and it is also demonstrated in the Perl documentation. Neither Perl history does mention such a big change in the language.

1 Answers

Was this construct removed from Perl, or is this a bug?

From perldoc perlvar:

$_ is a global variable.

However, between perl v5.10.0 and v5.24.0, it could be used lexically by writing my $_ . Making $_ refer to the global $_ in the same scope was then possible with our $_ . This experimental feature was removed and is now a fatal error, but you may encounter it in older code.

 

If this was removed, I consider that a big problem as ...

I think this is not the right place to discuss this, i.e. discussions would not solve your current problem. As ikegami pointed out in the comments: this feature was marked experimental in 5.18 and thus led to warnings for many years. And you probably just need to replace the my $_ with local $_ in your code.

Related