develooper Front page | perl.perl5.porters | Postings from May 2019

[perl #134138] Eliminate modifiable variables in constants

Thread Previous
James E Keenan
May 25, 2019 02:03
[perl #134138] Eliminate modifiable variables in constants
Message ID:
# New Ticket Created by  James E Keenan 
# Please include the string:  [perl #134138]
# in the subject line of all future correspondence about this issue. 
# <URL: >

pod/perldeprecation.pod contains the following entry:

Constants from lexical variables potentially modified

You wrote something like

my $var; $sub = sub () { $var };

but $var is referenced elsewhere and could be modified
after the "sub" expression is evaluated. Either it is
explicitly modified elsewhere ("$var = 3") or it is passed
to a subroutine or to an operator like "printf" or "map",
which may or may not modify the variable.

Traditionally, Perl has captured the value of the variable
at that point and turned the subroutine into a constant
eligible for inlining. In those cases where the variable
can be modified elsewhere, this breaks the behavior of
closures, in which the subroutine captures the variable
itself, rather than its value, so future changes to the
variable are reflected in the subroutine's return value.

If you intended for the subroutine to be eligible for
inlining, then make sure the variable is not referenced
elsewhere, possibly by copying it:

my $var2 = $var; $sub = sub () { $var2 };

If you do want this subroutine to be a closure that
reflects future changes to the variable that it closes
over, add an explicit "return":

my $var; $sub = sub () { return $var };

This usage has been deprecated, and will no longer be
allowed in Perl 5.32.

The entry was made in this commit:

commit 9840d1d66ee1648f6d7fb1554101450158cfee16
Author: Abigail <>
Date:   Sat Jan 14 18:25:48 2017 +0100

Deprecating the modifyable variables in constants by 5.32.

It was already deprecated, but we're now adding a version number.

Make it so.

Thread Previous Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About