in reply to Why no stay shared warning?

The normal idiom for a "static local" variable is to declare it inside a BEGIN block, and put the acccessor subroutines within that same block. Just add BEGIN to your block, and you're done!
up(); up(); print get(); BEGIN { my $foo = 1; sub up { $foo++; sub get {$foo} } }
This is needed because you need the block executed once in order for the variable to go into and then out of scope, forming a closure with your two named subroutines.

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
Re: Re: Why no stay shared warning?
by danger (Priest) on May 05, 2001 at 21:48 UTC

    Note, a BEGIN block isn't necessary -- a bare block is fine as long as it is defined prior to the sub calls. Also, a BEGIN block may not always be the appropriate mechanism:

    #!/usr/bin/perl -w use strict; use Getopt::Std; my %opt; getopt('n',\%opt); BEGIN { my $foo = $opt{n}; sub up { $foo++; sub get {$foo} } } up(); up(); print get();

    Now, if you comment out the BEGIN line above it will work as one might have expected. Not that I think this might be a common problem, but I thought it might be worthwhile to highlight the difference.