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]
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.