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

Well, I use require to use a module during runtime.
In this module I try to access a variable from the main program (i.e. $main::project). This doesn't work. I get allways an undef for this variable.
Is this normal?

In another program I use use instead of require and all works fine. But in this special case I need to use require!

Any hints are welcome.
Thx

----------------------------------- --the good, the bad and the physi-- -----------------------------------

Replies are listed 'Best First'.
Re: require & $main::variables
by davorg (Chancellor) on Apr 03, 2001 at 12:34 UTC

    How do you declare $project within your main package? My initial thought is that you're declaring it using my, in which case it's a lexical variable, not a package variable and won't be visible from outside the main file.

    If that's not right, perhaps you can post a cut-down versnio of the code which exhibits this behaviour.

    --
    <http://www.dave.org.uk>

    "Perl makes the fun jobs fun
    and the boring jobs bearable" - me

      Yeep, that was it. Now I use our in main and it works with require. Thanks.
      But in another program it works with use and my in the main program.

      Maybe require is a little bit different from use in that case.

      ----------------------------------- --the good, the bad and the physi-- -----------------------------------

        Read up on require and use ... they are indeed different (use requires the file and then imports all the variables the file exports.)
        perlfunc:require
        perlfunc:use

        Philosophy can be made out of anything. Or less -- Jerry A. Fodor

Re (tilly) 1: require & $main::variables
by tilly (Archbishop) on Apr 04, 2001 at 04:16 UTC
    The code:
    use foo qw/bar $baz/;
    is the same as:
    # Do this at compile time.... BEGIN { # load if needed require foo; # import functionality foo->import('bar', '$baz'); }
    Most errors (not this one, but most) where a require did not do what a use would are missing the import.

    UPDATE
    As merlyn points out, if your require does not match what you expected from use, and it wasn't a missing import, then likely you need the BEGIN block. Or else (as in this case) it is an unrelated mistake and the use wouldn't have worked either.

      Most errors (not this one, but most) where a require did not do what a use would are missing the import.
      ... or the fact that it's in a BEGIN block.

      -- Randal L. Schwartz, Perl hacker