Import problem

J

J Krugman

If I do

use strict;
my $bar;
use Foo '%Bar';
BEGIN {
$bar = \%Bar;
}

my script compiles fine, but when I try

use strict;
my $bar;
BEGIN {
require Foo;
Foo->import('%Bar');
$bar = \%Bar;
}

I get a compilation error ('Global symbol "%Bar" requires explicit
package name...'). What's wrong with the second version?

TIA,

jill
 
M

Malcolm Dew-Jones

J Krugman ([email protected]) wrote:


: If I do

: use strict;
: my $bar;
: use Foo '%Bar';
: BEGIN {
: $bar = \%Bar;
: }

: my script compiles fine, but when I try

: use strict;
: my $bar;
: BEGIN {
use vars qw(%Bar); ### add this
: require Foo;
: Foo->import('%Bar');
: $bar = \%Bar;
: }

Or try

use strict;
my $bar;
BEGIN {
BEGIN {
require Foo;
Foo->import('%Bar');
}
$bar = \%Bar;
}


: I get a compilation error ('Global symbol "%Bar" requires explicit
: package name...'). What's wrong with the second version?


The export that happens during use Foo '%Bar'; has the same effect on the
variable as the use vars pragma. Because use Foo happens at compile time,
therefore %Bar is known to perl when it finds it later in the code. In
your second example you only do a require and import. Because they happen
at run time, the %Bar is not known to perl at compile time. So, either
run the require/import as part of the compile (i.e. BEGIN), or do
something else at compile time to make the variable known (i.e. use vars).

"our" would presumably work also.
 
C

ctcgag

J Krugman said:
If I do

use strict;
my $bar;
use Foo '%Bar';
BEGIN {
$bar = \%Bar;
}

my script compiles fine, but when I try

use strict;
my $bar;
BEGIN {
require Foo;
Foo->import('%Bar');
$bar = \%Bar;
}

perldoc perlmod:
A "BEGIN" subroutine is executed as soon as possible, that is, the
moment it is completely defined, even before the rest of the containing
file is parsed.


So BEGIN doesn't execute line by line, but only once the whole thing is
compiled, i.e. not until the closing } is parsed. So the %Bar dies during
the compiling of the BEGIN block because the import has not been executed
yet (although it has been compiled). So move the \%Bar after the BEGIN
block.

Xho
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top