On 11/15/05, John Doe <[EMAIL PROTECTED]> wrote: > David Baird am Dienstag, 15. November 2005 11.07: > > On 11/15/05, John Doe <[EMAIL PROTECTED]> wrote: > > > Jeremy Nixon am Dienstag, 15. November 2005 08.06: > > > > Peter1 Alvin <[EMAIL PROTECTED]> wrote: > [...] > > > > { # start a lexical scope > > > > my %d_cache; > > > > sub handler { > > > > # stuff > > > > if (not defined($d_cache{$foo})) { > > > > # pull in directory listing and store it in $d_cache{$foo} > > > > } > > > > # proceed to use $d_cache{$foo} information > > > > } > > > > } end lexical scope > > > > > > > > This way, a directory is only actually read once (at most) per server > > > > child process. > > > > > > Hi Jeremy > > > > > > Hope it's not a stupid question, but are you sure %d_cache survives a > > > request? Maybe I'm totally misunderstanding something but I thought after > > > the point > > > > > > } end lexical scope > > > > > > %d_cache gets destroyed (if not still referenced from somewhere else). > > > > > > I would have left out the scope-{} to keep %d_cache at file level. > > > Would that be wrong? And why? > > > > The handler() sub stays in scope - it's basically a global variable, > > and it holds a reference to %d_cache. So %d_cache goes out of scope, > > but doesn't get destroyed. It hangs around until the next time > > handler() is called, at which point you're back in the same scope and > > can access %d_cache again. > > Hi David > > thanks a lot for your answer! I have still a last question to get it 100%: > > The (lexical scoped) code as shown above does _not_ show the required > referencing of %d_cache, right? Something like > > if (not defined($d_cache{$foo})) > > is not sufficient, right? > > Whereas something like > > $keep_ref=\%d_cache; > > in the handler() would, right? > > (If I'm not right, I didn't get something basic right, although I read a lot > of documentation about this issue... I would have to review/change a lot of > code I've written) > > Thanks a lot in advance >
No, the 'reference' to the lexical variable doesn't need to be a 'Perl reference', just some mention of the variable in the code. That will make it stick around, but only within the lexical scope specified. d.