use v5.30;
use strict;
use warnings;
{
my $add = 0;
sub getter { $add }
sub counter {
my @nums = (1..500);
for my $num (@nums) { $add += $num; }
}
}
counter();
say "getter => ", getter();
Though, just returning a value from counter() seems better practice:
use v5.30;
use strict;
use warnings;
sub counter {
my $add = 0;
my @nums = (1..500);
for my $num (@nums) { $add += $num; }
return $add;
}
my $got = counter();
say "got => ", $got;
I've never been a big fan of state, there are not many patterns (if any) which can't be implemented with closed over my declarations.
The state keyword is mostly just syntactic sugar. The following are essentially the same:
{
my $foo = 123;
sub myfunc {
...;
}
}
sub myfunc {
state $foo = 123;
...;
}
The latter allows you to eliminate a level of nesting. Also in the case where the value being assigned to $foo is expensive to calculate, it means you won't need to calculate it until myfunc is actually called (which might be never in some cases). If you don't care about undef/false values, you can kind of emulate that using:
{
my $foo;
sub myfunc {
$foo ||= 123;
...;
}
}
|