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

If i call a subroutine and say call it again at a later time will the old values of the variables within the subroutine still exist?

Replies are listed 'Best First'.
Re: my variables in a subroutine
by ikegami (Patriarch) on Mar 23, 2009 at 04:06 UTC

    Depends where you declare it.

    my $keeps_value; sub func { my $loses_value; state $also_keeps_value; # Perl 5.10 ... }
Re: my variables in a subroutine
by cdarke (Prior) on Mar 23, 2009 at 08:57 UTC
    Further to ikegami's post, in case you are not using 5.10 yet, the following 'hack' works as well:
    use strict; use warnings; { # Outer block my $keeps_value = 0; sub mysub { print "$keeps_value\n"; $keeps_value++ } } # End of outer block mysub(); mysub(); mysub();
    Produces:
    0 1 2
    The varibale $keeps_value is not visible outside the block.
      Your example isn't a hack as such, it is, as lakshmananindia pointed out, a closure.

      A user level that continues to overstate my experience :-))
        Semantics, one man's hack is another's feature. I view it as a hack because it fulfills functionality missing from the language, i.e. a 'state' variable type (aka 'static') (and if it wasn't a missing feature then it wouldn't have been added).
Re: my variables in a subroutine
by lakshmananindia (Chaplain) on Mar 23, 2009 at 03:51 UTC

    Refer How to post a question

    I think you need closures. If not, please explain your question?

    Read closures in Advanced Programming in perl by Sriram srinivasan

    --Lakshmanan G.

    Your Attempt May Fail, But Never Fail To Make An Attempt

Re: my variables in a subroutine
by tilly (Archbishop) on Mar 23, 2009 at 18:56 UTC
    In addition to the other answers, there is a bug around the construct my $foo if condition(); that causes previous values to be kept when condition() is false. I would highly recommend that any large codebase be grepped for variations on this construct - usually it causes a subtle bug that would be hard to track down.