faqts : Computers : Programming : Languages : Perl

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

16 of 20 people (80%) answered Yes
Recently 8 of 10 people (80%) answered Yes


Is there a way to get a locally scoped, STATIC variable in a Perl function?

Apr 3rd, 2001 10:52
Chris Riley, Kyle Olsen, The Camel Book

my will create a locally scoped variable. The trick is to avoid having 
it get garbage collected. You need to make sure that the variable isn't 
being used. To do this you need to put the variable and function in 
another lexical block. Then you need to make sure that the block is run 
before the main program.
Try something like this:
    my $count = 0;
    sub increment { return ++$count; }
This will work in Perl 5.6
[[paraphrased from the camel book, 3rd ed. p 223]]