|Syntactic Confectionery Delight
Making a variable in a sub retain its value between callsby crashtest (Curate)
|on Apr 18, 2005 at 20:27 UTC
crashtest has asked for the wisdom of the Perl Monks concerning the following question:
Wise Monks, This morning I was writing a subroutine that needed to keep track of some simple data between calls. Because the data in question was really local to the subroutine, I didn't want to pass a reference to it on each call, especially since this reference would have had to go through a number of other enclosing functions first. I wanted a variable that was limited to the subroutine's scope, but would retain its value between subroutine calls. I can't help but suspect this need stemmed from some poor program design somewhere, but there I was, and that was what I needed. I realized (with horror) that I was looking for something similar to VisualBasic's Static Modifier. Luckily I left VB and other MS technology behind me some time ago, so I just did something similar to the following:
I suppose this works well enough, and it seems fairly clean to me. But I was curious if there was some other way to get this behavior, and what Real Perl Programmers do in these cases. Is there a clever way to accomplish what I want without the enclosing block? Some trickery to be found on CPAN, perhaps? Thanks in advance for your input. Please don't flame me too hard for having used VB!