I don't recall any of the discussions of Perl 6 mentioning static variables. There aren't any good ways to get static variables in Perl 5. The best is probably:
but that won't work under mod_perl (and, well, it also sucks quite a bit).{ my $static; BEGIN { $static= "Initial value" } sub usesStatic { # ... } }
Several times I've mentioned that I'd like to see BEGIN (and a few other similar "keywords") be supported as statement modifiers, in part so that we could have real static variables in Perl:
but never with much visibility. [sub usesStatic { my $static= "Initial value" BEGIN; # ... }
]Note that this would function quite a bit like
but without being a horrid hack that many consider to be bug (and you could provide an initial value and Perl would be smart enough to make $static so that it does "stay shared" if you used nested subroutines for some strange reason such as mod_perl).sub usesStatic { my $static if 0; # ... }
I really like that the BEGIN makes it clear that the initialization code is going to run at compile time and that you could instead say, for example, CHECK if you want the initialization to happen a bit later.
So I wanted to raise the visibility of this idea. I also was hoping someone had some insight into what plans, if any, there are for static variables in Perl 6. Depending on the feedback I get here, I may post this suggestion to a Perl 6 discussion list.
Note that you could also use this for other things. If there was also a way to use eval without introducing an extra layer of scope, then you could do lots of really fun things akin to source-code macros:
where the "conditional code" could, for example, declare lexicals, which could be really cool (and dangerous).eval q{ conditional code; } if condition BEGIN;
Update: Note that global variables ("package" variables) are also a form of static variable and they have some advantages ove the "best" version I provided above. They also have some disadvantages (being global), otherwise the "best" version would have never been thought up. Feel free to think "non-global static" or "static lexical" whenever you read "static" above if that helps. (:
- tye (but my friends call me "Tye")
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Static variables (and also Perl 6)
by clintp (Curate) on Jan 26, 2002 at 05:13 UTC | |
by tye (Sage) on Jan 26, 2002 at 12:22 UTC | |
by tilly (Archbishop) on Jan 27, 2002 at 22:59 UTC | |
by TheDamian (Vicar) on Apr 10, 2002 at 00:56 UTC | |
|
Re: Static variables (and also Perl 6)
by Juerd (Abbot) on Jan 26, 2002 at 01:29 UTC | |
|
Re: Static variables (and also Perl 6)
by Juerd (Abbot) on Jan 26, 2002 at 22:07 UTC | |
by tilly (Archbishop) on Jan 27, 2002 at 07:08 UTC | |
by theorbtwo (Prior) on Jan 27, 2002 at 01:51 UTC | |
|
Re: Static variables (and also Perl 6)
by ignatz (Vicar) on Jan 26, 2002 at 01:45 UTC |