in reply to (tye)Re: Static variables (and also Perl 6)
in thread Static variables (and also Perl 6)

Try this out:
my $static := BEGIN {my $foo = "default value"};
If I am not mistaken, the BEGIN block should initialize its variable at compile time, and always return the same variable thereafter. The my variable that you are declaring is then made an alias to this returned variable. Because it is declared lexically, it is available in a lexical scope only.

If that doesn't work, then some fairly straightforward variant on it should.

This construct is embeddable in any scope you want. And so you can embed it in inner blocks as well. Figure out how to add syntactic sugar, and spice to taste. :-)

Replies are listed 'Best First'.
Re: I think this would be a static in Perl 6?
by TheDamian (Vicar) on Apr 10, 2002 at 00:56 UTC
    Yep. I believe that that works exactly as tilly suggested. Way cool. Wish I'd thought of it. Here's an interesting variant:
    my ($static1, $static2) := *BEGIN{["val1","val2"]};
    (Note the implicit enreferencing of the array reference returned by the BEGIN block, which happens because the "flattening *" expects an array.)