fionbarr has asked for the wisdom of the Perl Monks concerning the following question:

I have a program 'a.pl' which 'requires' b.pm in which resides a sub-routine. I call the subroutine many times...in the subroutine are a number of local variables that need initialization. How/where can I initialize these ONE time only so they retain their value and each invocation of the subroutine does not re-init these variables? I'm sure this is an easy one but the answer is not obvious to me. Thanks.

Replies are listed 'Best First'.
Re: variables in modules
by pc88mxer (Vicar) on Jun 16, 2008 at 16:56 UTC
    You can provide an initialization routine in b.pm to set your variables:
    # -- file b.pm my ($var1, $var2, $var3); sub initialize_variables { $var1 = shift; $var2 = shift; ... } sub routine { # use $var1, $var2, etc. } 1;
Re: variables in modules
by jettero (Monsignor) on Jun 16, 2008 at 16:58 UTC

    use vars would do the trick. I'd probably use our.

    sub p1 { our $persistant; $persistant = "init" unless defined $persistant; $persistant .= "."; return $persistant. }

    Of course, that's going to be global to the package namespace, so if you need more than one type of p1(), maybe bless can help too.

    package niffty; sub new { bless { persistant => "init" } } sub p1 { my $this = shift; $this->{persistant} .= "."; return $this->[persistant}; }

    -Paul