DEVFYI - Developer Resource - FYI

How do you give functions private variables that retain their values between calls?

Perl Questions and Answers


(Continued from previous question...)

How do you give functions private variables that retain their values between calls?

Create a scope surrounding that sub that contains lexicals.
Only lexical variables are truly private, and they will persist even when their block exits if something still cares about them. Thus:
{ my $i = 0; sub next_i { $i++ } sub last_i { --$i } }
creates two functions that share a private variable. The $i variable will not be deallocated when its block goes away because next_i and last_i need to be able to access it.

Other Interview Questions