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

Q

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

✍: Guest

A

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.

2013-09-25, 1999👍, 0💬