in reply to Lexical and dynamic scope confusion!
A little trial and error would answer the question as to what happens, although maybe not the "why" part. Here's what I wrote:
Note the "use Foo" is commented out - because I put this all in the same file, you can't quite do that, so I faked it with the next line - and the BEGIN is very important here. By using the BEGIN, it changed the output. With the BEGIN, I get "main::sub1" as the output, but without the BEGIN, I get "Foo::sub1" as the output.use strict; use warnings; package Foo; use base 'Exporter'; our @EXPORT = qw(sub1); our @EXPORT_OK = qw(sub1 sub2); sub sub1 { print "Foo::sub1\n"; } sub sub2 { print "Foo::sub2\n"; } package main; #use Foo; BEGIN { Foo->import(); } sub sub1 { print "main::sub1\n"; } sub1();
With the BEGIN is representative of "use"ing the module since "use" is handled during compilation, as is anything in a BEGIN block.
I know others disagree with this, but the way I handle the ambiguity is to try to import as little as possible into my namespace - preferably importing nothing. And then I can call functions in other namespaces by fully qualifying the function call.
Even better than that is to use an OO interface, if there is one available, but not everything makes sense as an object. (I think CGI does, but that's not necessarily universally accepted, either.)
In absense of these (calling functions via fully qualified names, or OO syntax), import precisely what you need, no more, no less. This means you get to keep an exact list of what you're using from another module, and won't be as likely to have two functions in your module's namespace with the same name.
It is highly discouraged to try to use a function "sub1" from another module, while exporting a different "sub1" from your own module. You're looking for a headache on that one - fully qualified names (for calling the other module's sub1, not for exporting your sub1) or OO syntax are quite a bit cleaner here.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Lexical and dynamic scope confusion!
by tlm (Prior) on Mar 27, 2005 at 15:58 UTC |