mellin has asked for the wisdom of the Perl Monks concerning the following question:

I tried looking help from perldoc.com, but it wasn't much useful at the matter. I use a require function in my index.pl script, the meaning of the function is to include selected code, if it is needed. Now, a short example looks like this
my $relative_map = 'relative.lib'; require "$cgi_dir/$sub_search_form" unless ($gbook);
That required code is a normal perl-code, without any sub-programs, but that $relative_map variable just doesn't get passed to it? I have understood that variable defined as lexical can be read from anywhere in the current 'scope', but not higher from the point where defined. (i can't explain this better, english not native language..) Simply put: why can't that required code read that variable?

Replies are listed 'Best First'.
Re: require function not passing lexical variable
by Fletch (Bishop) on Nov 12, 2004 at 19:56 UTC

    require FILENAME behaves similar to do FILENAME, and if you check out perldoc -f do you'll see:

    It also differs in that code evaluated with "do FILENAME" cannot see lexicals in the enclosing scope; "eval STRING" does.
Re: require function not passing lexical variable
by tilly (Archbishop) on Nov 12, 2004 at 21:39 UTC
    As Fletch said, the documentation says that it does not. But he didn't explain why it does not.

    The reason why is that require means "make sure that this code has been run", and not "insert this code here". The same file can be required in many places, but will only be run once, in a scope of its own.