[Kc] complex initialization of a state variable in current perl (5.8.7)

David Nicol davidnicol at gmail.com
Wed May 9 09:21:03 PDT 2007


On 5/8/07, Garrett Goebel <ggoebel at goebel.ws> wrote:
> > use strict;
> >
> >>> defined $hr and die "$hr is defined outside of scope";
> gives:
> > Global symbol "$hr" requires explicit package name at foo.pl line 11.
> > Global symbol "$hr" requires explicit package name at foo.pl line 11.
> > Execution of foo.pl aborted due to compilation errors.
>
> cheers,
>
> Garrett

line 11 was the verification that $hr wasn't leaking outside the
scope, so it is well and good and not a problem with the approach
that turning stricture on caught it.

calling foo multiple times will verify that $hr is
a state variable.  Here it is again, with a demonstration
of the different timing of INIT and BEGIN.

sub foo{
        my $x if 0;
        INIT{
                $x  = 23
        }
        @_ and $x = shift;
        print $x,"\n";
};

BEGIN {foo(); foo(1); foo()}

foo();
foo(22);
foo();
foo('cheese');
foo();


What I'm working towards here is talking about creating a ONCE
block, which would evaluate once the first time the code path passes
by it and then optimize itself away, like the /o regex modifier, which
would be more appropriate for use in initializing state variables
than any of the timing blocks.  Of course there's always

       my $guard if 0;
       unless($guard++ ){  ... once block goes here ...}

but that doesn't optimize itself out (and it will run the block again every
four billion times or so, or something, depending on how infinity gets
handled, and what the truth of +Inf of NaN or whatever it is is)


-- 
practical solutions to systemic problems


More information about the kc mailing list