good chemistry is complicated, and a little bit messy -LW |
|
PerlMonks |
Re^3: Easiest way to do something only on first iteration of loopby Marshall (Canon) |
on May 07, 2016 at 03:07 UTC ( [id://1162424]=note: print w/replies, xml ) | Need Help?? |
Mr. Muskrat++ for other alternatives.
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. 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".
In Section
Seekers of Perl Wisdom
|
|