Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: How to access main package global vars in modules

by GhodMode (Pilgrim)
on Apr 02, 2012 at 14:23 UTC ( [id://963018]=note: print w/replies, xml ) Need Help??


in reply to How to access main package global vars in modules

I had a very similar problem. This thread came up first in search resultes, but it didn't help me to understand the problem better. I'm sharing my experience here so that it may help the next person who finds this page in search results.

The thread that helped me most is Variable Scoping in Perl: the basics

The key is paying attention to the difference between the scope and the package. When you use my, it only declares a variable in the current scope, not in the current package. So, variables in a module that are declared with my in that module aren't accessible using the package name of the module, e.g. $main::var1.

To declare variables in the current package and the current scope, use our.

In my case, I wanted a global $logfile variable that I could reference in my module, but I wasn't able to access the main script's $logfile variable from the module's subroutine even if I used the fully-qualified name.

The solution that worked best for me is to set $ModulePackage::logfile whenever I set the $logfile variable in the main script. I could have as easily declared the our $logfile in the main script, but then I would have had to use the fully-qualified name in the module.

Also see package variable scope in module subroutine @ StackOverflow.

--
Ghodmode
www.ghodmode.com
  • Comment on Re: How to access main package global vars in modules

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://963018]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2024-04-26 07:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found