Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

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?

like image 575
nfanta Avatar asked Jan 27 '26 06:01

nfanta


1 Answers

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.

like image 144
melpomene Avatar answered Jan 29 '26 00:01

melpomene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!