on Tue, 16 Apr 2002 18:01:28 GMT, Richard Noel Fell wrote:

> If in a subroutine, I have a statements
> 
> sub
> {
> 
> my $local_var=1
> ....
> 
> 
> $local_var=$local_var+1;
> ....
> 
> }
> then the next time I run this subroutine, $local_var is reinitialized to
> 1. However, I would like to have it retain its value from the previous
> call to the subroutine. For example, if $local_var is 5 at the end of
> the subroutine call, then it would have this initial value the next time
> the subroutine is called. This can be done by making $local_var a global
> variable which I do not want to do. Is there a way to achieve what I am
> trying to do and still retain $local_var as a local variable, sort of
> what is called a static variable in C, I think?

Yes, by enclosing the local variable and the subroutine in their own block  
(and essentially creating a closure):

        #! /usr/bin/perl -w
        use strict;

        {
                my $static_variable = 1;
        
                sub increment {
                        $static_variable++;
                        print "Static variable is now $static_variable\n";
                }
        }

increment();
increment();

        

-- 
felix

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to