nfanta nfanta - 5 months ago 12
Perl Question

Perl - why is necessary to specify the use of 'state' feature?

While learning Perl I came across this issue while trying to make a function that remembers previous values.

The code:

use strict;
use warnings;

sub running_sum {
state $sum;
state (@numbers);

foreach my $number (@_) {
push @numbers, $number;
$sum += $number;
}

$sum;
}

print running_sum(1..2);
print running_sum(3..5);


When I try to run it, I receive this errors:

Global symbol "$sum" requires explicit package name (did you forget to declare "my $sum"?) at ../tmp.pl line 12.
Global symbol "@numbers" requires explicit package name (did you forget to declare "my @numbers"?) at ../tmp.pl line 13.
Global symbol "@numbers" requires explicit package name (did you forget to declare "my @numbers"?) at ../tmp.pl line 16.
Global symbol "$sum" requires explicit package name (did you forget to declare "my $sum"?) at ../tmp.pl line 17.
Global symbol "$sum" requires explicit package name (did you forget to declare "my $sum"?) at ../tmp.pl line 20.


The function works well and doesn't throw any errors if I add
use feature 'state';
; but from what I've read as from 5.10 this should be always enabled (I'm using Perl v5.22.1).

Could I have something odd on my interpreter or code, or is this an expected behavior?

Answer

This is expected. Features that introduce new keywords have to be explicitly enabled, in order to avoid breaking existing programs that may have defined a sub called e.g. state.

You can enable features with a use feature declaration or with e.g. use v5.12.0 (which requires a minimum perl version of 5.12.0 and enables all features available in that version).

See also perldoc feature and perldoc -f use.

Comments