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

I wonder if there is any way you could access a variable in the main section of the program from inside a package without explicitly passing it to the package? I would like to do something like this:
#!/usr/bin/perl -w $var="GG"; Mypackage::printthis(); package Mypackage; { sub printthis { print "VAR is: $var\n"; } }
The above code doesn´t work ofcourse becouse $var is not defined in MyPackage. Is there a way to make variables superglobal so that they will be accessable from inside all used packages?

Replies are listed 'Best First'.
Re: Access variable from inside a package?
by rovf (Priest) on Aug 18, 2009 at 08:38 UTC

    $main::var

    -- 
    Ronald Fischer <ynnor@mm.st>
Re: Access variable from inside a package?
by dsheroh (Monsignor) on Aug 18, 2009 at 10:53 UTC
    Why would you want to do that? False laziness?

    If your package relies on the availability of a global found in the main program (which would be $main::var, as already mentioned), then you will be unable to use it as a part of any program which does not contain that same variable and make it available as a global under the same name. In your example of what you (think you) want, using Mypackage in any program which does not provide a global $main::var will mean that you then have to remember to never call printthis.

    Packages should not impose requirements of this sort on the code which uses them.

    In most cases, the correct approach for sharing variables between a package and other code would be to define it in the package and export it to the code using the package. But that may not be well-suited to what you're actually attempting to accomplish. So what are you actually attempting to accomplish, so we can advise on the best way to do it?

Re: Access variable from inside a package?
by JavaFan (Canon) on Aug 18, 2009 at 09:38 UTC
    Is there a way to make variables superglobal so that they will be accessable from inside all used packages?
    No, that would beat the point of packages. If you want that, just don't use different packages.

    But you can make a package variable known in the entire lexical scope, regardless of the current package. That's what 'our' does. So if you write

    our $var = "CG";
    it ought to work.