From: "John W. Krahn" <[EMAIL PROTECTED]> > Robert Citek wrote: > > 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(); > > }
The error says that the foo() and bat() will only share the same $bar during the first call to foo(). Basicaly you should not define named subroutines inside some code that may be executed several times. {my $bar = 100; sub bat { return ++$bar; } } is OK, but while ($x < 5) { my $bar = 100; sub bat { return ++$bar; } } would not. Because each iteration of the loop, just like each invocation of the foo() subroutine creates a brand new variable, while the bar() still points to the first one. > > BEGIN { > > my $bar=100; > > sub foo { > > $bar++; > > return $bar; > > } > > } > 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 } > } Yes, this is how it's written most often. The BEGIN{} block may be a good idea though, it ensures the $bar is set just after the subroutine is compiled. so even if you define your subroutines at the end of the source and call this particular subroutine somewhere above, the variable is set: #!perl print foo(),"\n"; print foo(),"\n"; { # limit scope of $bar my $bar = 100; sub foo { ++$bar } } print foo(),"\n"; print foo(),"\n"; vs. #!perl print foo(),"\n"; print foo(),"\n"; BEGIN { # limit scope of $bar my $bar = 100; sub foo { ++$bar } } print foo(),"\n"; print foo(),"\n"; Jenda ===== [EMAIL PROTECTED] === http://Jenda.Krynicky.cz ===== When it comes to wine, women and song, wizards are allowed to get drunk and croon as much as they like. -- Terry Pratchett in Sourcery -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]