Robert Citek wrote:
> 
> Hello all,

Hello,

> I want a variable to be memoized, that is, keep the variable available only
> to the function and the value remembered across invocations.  So far, I
> have created two versions listed below, both of which "work."  The first
> version prints a warning message 'Variable "$bar" will not stay shared ...'
> which I would like to avoid by coding The Right Way(TM).  Also, I wonder if
> the second version is modular enough so that it can be put in a module and
> loaded.
> 
> Is there a better way to memoize?
> 
> ------
> 
> #!/usr/bin/perl -wl
> # version 1
> use strict
> 
> sub foo {
>   my $bar=100;
>   sub bat {
>     $bar++;
>     return $bar;
>   }
>   return bat();
> }
> 
> print foo();
> print foo();
> print foo();
> 
> ----------
> 
> #!/usr/bin/perl -wl
> # version 2
> use strict
> 
> BEGIN {
> my $bar=100;
> sub foo {
>   $bar++;
>   return $bar;
> }
> }
> 
> print foo();
> print foo();
> print foo();

If you want memoize you can get the Memoize module:
http://search.cpan.org/author/MJD/Memoize-1.01/ but it looks like you
want a closure instead.  All you need to do is limit the scope of the
variable so that only the sub can see it.

{ # limit scope of $bar
my $bar = 100;
sub foo { ++$bar }
}


John
-- 
use Perl;
program
fulfillment

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

Reply via email to