in reply to Re: Eval doesn't see lexicals
in thread Eval doesn't see lexicals

Okay, I think I understand.

Variables that perl doesn't see being used get cleaned up when going out of scope. The variables go out of scope when the end of the file is reached which is why the code malfunctions when in a separate file.</>

I take it that variables still hang around at the start of a new package even though they are no longer directly acessible ( I am supposing that putting { and } around the entire package would change this, at least the samples for Class::Std do it, and there would have to be a reason.)

It makes sense, but it's pretty obscure ... thanks to all for your input.

Replies are listed 'Best First'.
Re^3: Eval doesn't see lexicals
by tilly (Archbishop) on Nov 02, 2005 at 02:53 UTC
    Mostly right.

    The quibble is that I strongly suspect some confusion about how lexical scope works. Coping with Scoping may clarify that. In short, a package declaration affects global variables, not lexical. So lexical variables in scope remain in scope across the package declaration. Like this:

    my $foo = "bar"; package Baz; print "$foo\n"; # prints bar
    Hence the braces as done in the examples for Class::Std serve the purpose of making lexical scope match package scope. Which is important when you're going to want separate lexical variables with the same name.
Re^3: Eval doesn't see lexicals
by dave_the_m (Monsignor) on Nov 02, 2005 at 10:39 UTC
    I take it that variables still hang around at the start of a new package even though they are no longer directly acessible ( I am supposing that putting { and } around the entire package would change this, at least the samples for Class::Std do it, and there would have to be a reason.)
    No, source code files are already treated as if they were surrounded by { and }, and variables are normally freed at the end of executing the included file. If a sub in that file captures the variable, then its lifetime is extended, but only that sub can subsequently access the retained value. For example:
    # Foo.pm my $var = 1; sub a { eval '$var' # sees an undefined value when later called } sub b { $var; eval '$var'; # sees 1 because b() has captured $var }
    Note that the variable's lifetime is extended merely by the existence of b(), but even with the existence of b(), a() cannot see the variable.

    Dave.