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:
use strict;
use warnings;
test() for (1..3);
{
my $memory = 0;
sub test{
print "Value of static var is ", $memory++, "\n";
}
}
__END__
Value of static var is 0
Value of static var is 1
Value of static var is 2
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!
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.