circular import doesn't behave as expected?


A

asokoloski

So I have two modules:

=== a.pm ===
package a;
use b;

sub import {
print "import in $_[0] called from ". (caller(1))[3] ." \n";
}

1;
=== b.pm ===
package b;
use a;

sub import {
print "import in $_[0] called from ". (caller(1))[3] ." \n";
}

1;
==========

and a script:

=== test.pl ===
#!/usr/bin/perl

use strict;
use warnings;

use a;
==========

Running this script prints:
--------------
import in b called from a::BEGIN
import in a called from main::BEGIN
--------------
Whereas I would expect there to be another "import in a called from
b::BEGIN" at the beginning, from the "use a;" in b.pm. I know that
each module is only compiled once, but import should be called each
time, and there are three "use" statements, so shouldn't there be three
imports?

What am i missing here?

Thanks,
Aaron
 
Ad

Advertisements

B

Bob Walton

So I have two modules:

=== a.pm ===
package a;
use b;

sub import {
print "import in $_[0] called from ". (caller(1))[3] ." \n";
}

1;
=== b.pm ===
package b;
use a;

sub import {
print "import in $_[0] called from ". (caller(1))[3] ." \n";
}

1;
==========

and a script:

=== test.pl ===
#!/usr/bin/perl

use strict;
use warnings;

use a;
==========

Running this script prints:
--------------
import in b called from a::BEGIN
import in a called from main::BEGIN
--------------
Whereas I would expect there to be another "import in a called from
b::BEGIN" at the beginning, from the "use a;" in b.pm. I know that
each module is only compiled once, but import should be called each
time, and there are three "use" statements, so shouldn't there be three
imports?

What am i missing here?

Try defining your sub import{} first, as in for a.pm:

package a;
sub import {
print "import in $_[0] called from ". (caller(1))[3] ." \n";
}
use b;
1;

Does that help? When I run it that way, sub import for package a
prints twice. It is a question of whether your sub import is
defined at the time of the call to import. Recognize that the
calls to import() made by use() are occuring at compile time, and
not everything has necessarily been compiled yet.
 
Ad

Advertisements

A

asokoloski

Yup, it does. Thanks everyone!

I fixed the real problem, by the way, by putting the initialization for
"@EXPORT" and such in a BEGIN block. But I wouldn't have thought of it
by myself.
 

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

Top