in reply to Re^2: Easiest way to do something only on first iteration of loop
in thread Easiest way to do something only on first iteration of loop
See State Variable. A
a "state" variable is a special kind of "my" variable that
is not re-initialized ever again. Its value will persist for the life of the program. in the loop when it is seen again. When it is "out of scope", then next time it comes into scope it is reinitialized. Was new in Perl v5.10.
See each for arrays. each with this behavior was new in Perl 5.12 and this was also new to me.
No there is no "magic" short easy syntax for what you want to do in the general case, but you are using a common pattern that is easily recognizable. "Once upon a time, there was a princess...", we know what this story is going to be about! Good variable name like $first_time, etc. provides huge clues that something is special at the beginning. I wouldn't worry much about it.
Update: My mistake. Thanks to Athanasius for catching this issue. The state variable is never re-initialized, even if it goes out of scope and then comes back into scope. The analogy in the documentation to a "my" variable caused a brain cramp when I read the spec. A state variable is called a "Persistent Private Variable".
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Easiest way to do something only on first iteration of loop
by Athanasius (Archbishop) on May 08, 2016 at 06:53 UTC | |
by Marshall (Canon) on May 08, 2016 at 12:21 UTC | |
by BrowserUk (Patriarch) on May 08, 2016 at 12:48 UTC |