G'day pritesh_ugrankar,
Some preamble:
Your 'use 5.030;' will give you an automatic 'use strict;' but not a 'use warnings;'.
It would've been better to start with:
use 5.030;
use warnings;
For the code you've posted, you only need 'use 5.010;' for state and say,
see perl5100delta;
and 'use 5.012;' to get the 'use strict;', see use.
In the following, I've used an alias of mine I commonly use for testing:
$ alias perle
alias perle='perl -Mstrict -Mwarnings -Mautodie=:all -MCarp::Always -E
+'
and, my Perl version is 5.32.0:
$ perl -v | head -2 | tail -1
This is perl 5, version 32, subversion 0 (v5.32.0) built for cygwin-th
+read-multi
Here's an example of what you could have done that makes sense of the use of state
(using slightly easier to follow numbers):
$ perle '
say counter() for 1..3;
sub counter {
state $add;
$add += $_ for (1..5);
return $add;
}
'
15
30
45
You could've also assigned the return value and used it later.
This example also shows two $add variables, used in different lexical scopes, with no conflict.
$ perle '
my $add;
for (1..3) {
$add = counter();
say "... other processing here ...";
say $add;
}
sub counter {
state $add;
$add += $_ for (1..5);
return $add;
}
'
... other processing here ...
15
... other processing here ...
30
... other processing here ...
45
|