in reply to Initialization of "local static" (style question)

If you want $myval to be private to &f, don't use our, use my in a block enclosing both, &f and $myval:

{ my $myval = myfunc(); sub f { ... }; };

Alternatively, if you are on Perl 5.10, you can use the new state keyword, which is basically the same but a bit more explicit. Also see About "state" variables in Perl 5.10 for some more discussion, also about the timing of the different initializations.

Replies are listed 'Best First'.
Re^2: Initialization of "local static" (style question)
by rovf (Priest) on Feb 03, 2009 at 11:19 UTC
    use my in a block enclosing both

    I had thought that my function would not be visible outside the block then, but of course, functions are always global. Nice idea!

    I will remember it for use in a later project, though, because in my current one, the automatic documentation system requires that the documentation of a function appears immediately before the line starting with 'sub', which means that I would have to move the declaration of $myval in front of the function docs.

    -- 
    Ronald Fischer <ynnor@mm.st>
      One option would be to use closures.
      ## DOC: returns a function that does that and that. sub ff { my $myval=myfunc(); ... sub { g(++$myval) } } ... my $f = ff; ... my $x = $f->();
      []s, HTH, Massa (κς,πμ,πλ)
Re^2: Initialization of "local static" (style question)
by AnomalousMonk (Archbishop) on Feb 03, 2009 at 18:41 UTC
    The critical thing to remember about the closure trick in 5.8 (I'm not familiar with 5.10) is that  my variables are not initialized until runtime. This is touched on in About "state" variables in Perl 5.10. Making the closure blocks  BEGIN or  INIT blocks in 5.8 controls this, but you still must consider block ordering. See perlmod.

    Examples run under 5.8.2.

    >perl -wMstrict -le "print F(); { my $y = X(); sub F { return $y } } { my $x = 'foo'; sub X { return $x } } " Use of uninitialized value in print at -e line 1. >perl -wMstrict -le "print F(); BEGIN { my $y = X(); sub F { return $y } } BEGIN { my $x = 'foo'; sub X { return $x } } " Undefined subroutine &main::X called at -e line 1. BEGIN failed--compilation aborted at -e line 1. >perl -wMstrict -le "print F(); BEGIN { my $x = 'foo'; sub X { return $x } } BEGIN { my $y = X(); sub F { return $y } } " foo >perl -wMstrict -le "print F(); INIT { my $y = X(); sub F { return $y } } INIT { my $x = 'foo'; sub X { return $x } } " Use of uninitialized value in print at -e line 1. >perl -wMstrict -le "print F(); INIT { my $x = 'foo'; sub X { return $x } } INIT { my $y = X(); sub F { return $y } } " foo
    massa's function generator approach of Re^3: Initialization of "local static" (style question) gets around some of this.