in reply to my within a loop

In modern versions of Perl (I use 5.12) you can use the state keyword.

From the docs:

state declares a lexically scoped variable, just like my does. However, those variables will never be reinitialized, contrary to lexical variables that are reinitialized each time their enclosing block is entered. state variables are enabled only when the use feature "state" pragma is in effect.

But take care: even if you leave the loop entirely and re-enter it later, the state variable will still have maintained its last value!

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Replies are listed 'Best First'.
Re^2: my within a loop
by JavaFan (Canon) on Apr 05, 2011 at 10:17 UTC
    Using a state variable doesn't seem appropriate here. What the right thing to do here depends on "whatever". If "whatever" is the same all the time, and the value of the variable doesn't change, moving it outside of the loop is the right thing to do. Otherwise, it should be left as is. It's a common case, and perl actually optimizes this - from a language POV, you get a new variable each time. Internally, structures are reused if possible.