On Tue, 2002-04-16 at 14:01, richard noel fell wrote: > If in a subroutine, I have a statements > > sub > { > > my $local_var=1 > .... > > > $local_var=$local_var+1; > .... > > } > then the next time I run this subroutine, $local_var is reinitialized to > 1. However, I would like to have it retain its value from the previous > call to the subroutine. For example, if $local_var is 5 at the end of > the subroutine call, then it would have this initial value the next time > the subroutine is called. This can be done by making $local_var a global > variable which I do not want to do. Is there a way to achieve what I am > trying to do and still retain $local_var as a local variable, sort of > what is called a static variable in C, I think? > > Thanks, > Dick Fell
You can declare a my variable that doesn't get redefined like this. sub has_a_static_var { #declare a "static" variable my $static if 0; if (defined $static) { $static++ } else { $static = 0 } #do stuff } N.B. this is bad juju. You might consider using an our variable instead, the downside to that is namespace conflicts. If you define another our variable with the same name they point to the same variable; this is a feature (it is the main difference between our and my). example sub has_an_our_var { our $static; if (defined $static) { $static++ } else { $static = 0 } print "\$static in has_an_our_var = $static\n"; } The problem occurs when you write another function like this sub has_another_our_var { our $static; if (defined $static) { $static++ } else { $static = 0 } print "\$static in has_another_our_var = $static\n"; } then these function calls has_an_our_var(); has_another_our_var(); would print $static in has_an_our_var = 1 $static in has_another_our_var = 2 The third option is to use a closure, and there is already a good example of that in another reply. -- Today is Sweetmorn the 33rd day of Discord in the YOLD 3168 Or not. Missile Address: 33:48:3.521N 84:23:34.786W -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]