Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Variable Scoping in Perl: the basics

by thecap (Initiate)
on Nov 11, 2004 at 03:00 UTC ( [id://406891]=note: print w/replies, xml ) Need Help??


in reply to Variable Scoping in Perl: the basics

I have two files:
# inc.pl use vars qw($foo); $foo = "hello"; 1;
# t.pl use strict; use vars qw($foo); do 'inc.pl'; print $foo, "\n";
If I remove the 'use vars' from t.pl than t.pl fails to run with the error 'Global symbol "$foo" requires explicit package name'. How can I create a main:: global variable in inc.pl which I can access from t.pl without explicitly listing it in a 'use vars'?

I would like to have lots of variables in inc.pl without listing each of them in files that use them.

Thank you for any help.

Replies are listed 'Best First'.
Re^2: Variable Scoping in Perl: the basics
by arturo (Vicar) on Dec 29, 2004 at 22:20 UTC

    The text of the tutorial doesn't mention the fact that the scope of the effect of use vars is file-level. This is, however, documented in the perldoc for vars:

    the "use vars" and "use subs" declarations are not BLOCK-scoped. They are thus effective for the entire file in which they appear.
    (it's also mentioned under "Pragmatic Modules" in the perlmodlib man page).

    Even though its "maximum reach" is one file, the effects of use vars are still different than those of our, which was all I was trying to document in the tutorial.

    So, the general answer to your question is that you can't do exactly what you say you want to do, and that's one of the points of use strict: if you're going to use a variable in a file, you have to declare it explicitly in that file; it encourages you to know where everything's coming from, and protects you from typos in variable names.

    This doesn't mean your problem's insoluble, though. If, you want inc.pl to serve the function of being a "configuration script" that initializes a bunch of values so other scripts can use them, you can have it work this way: create one data structure (say, a hash), and 'export' that hash. This way, a script that uses inc.pl will only need to declare one variable with our or use vars; of course, with a hash, you lose the safety mentioned as one of the chief benefits of use strict.

    For this reason, instead of using a simple hash, you might want to have inc.pl be an object oriented module, but that's beyond the scope of this tutorial.

    HTH!

    If not P, what? Q maybe?
    "Sidney Morgenbesser"

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2024-04-19 00:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found