my @y = map { state $z = 0; $z += $_ } @x;
The use of the state scalar variable $z in the map BLOCK in this statement is neat, but it presents a stumbling block to which it is perhaps unwise to expose a novice lest he or she be precipitated, however inadvertently, from the True Path.
A state variable, of course, maintains its state from one access to the next regardless of whether or not the lexical scope enclosing the variable is exited and re-entered. This is fine if the statement containing the variable is executed once and only once in the execution of a program; if it is not, the results may be surprising. (In the example below the source array @w is repeatedly dumped just to show that it never changes.)
>perl -wMstrict -MData::Dump -lE "sub summer { return map { state $z = 0; $z += $_; } @_; } ;; my @w = qw(0 1 3 2); my @x = summer(@w); my @y; @y = map { state $z = 0; $z += $_; } @w for 1 .. 3; my @z = map { state $z = 0; $z += $_; } @w; ;; dd \@w; dd \@x; dd \@y; dd \@z; ;; @x = summer(@w); @y = map { state $z = 0; $z += $_; } @w for 1 .. 3; @z = map { state $z = 0; $z += $_; } @w; ;; print '----------'; dd \@w; dd \@x; dd \@y; dd \@z; ;; print '----------'; dd \@w; " [0, 1, 3, 2] [0, 1, 4, 6] [12, 13, 16, 18] [0, 1, 4, 6] ---------- [0, 1, 3, 2] [6, 7, 10, 12] [12, 13, 16, 18] [0, 1, 4, 6] ---------- [0, 1, 3, 2]
In reply to Re^2: adding items, but with interim results
by AnomalousMonk
in thread adding items, but with interim results
by kontrapunktstefan
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |