Suppose you have a method of a class that you write using Moose(but a plain Perl object is also relevant), and you use inside that method a static variable (static in the C sense, by that I mean a variable that has scope local to the method but a lifetime that spans each call of said method). I was recommended that I use a closure and enclose the declaration of that variable and the method inside the closure to cause the variable to be static(again, the C sense of static).
Mixing C-think and Perl-think is not always a good idea. What you are looking for is a state variable, and that is a feature that is new with 5.10 and has to be requested. No closure is required.
Pre-5.10 you do this with a closure.
{ # open an anonymous block to form the closure my $foo; my $bar; sub fubar { # code that uses $foo and $bar # goes in here } } # end of the closure
At the end of the closure the two variables go out of scope, but subsequent calls to fubar() still can use them without a problem.
- doug
In reply to Re: Some trouble with closures
by doug
in thread Some trouble with closures
by spx2
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |