tags:

views:

100

answers:

3

Let's say there are two modules that mutually use each other:

package a;
use b;
sub p {}

1;

package b;
use a;
1;

I think that it is systematically wrong to write code like the above, because the two modules will endlessly copy each other's code to themselves, but I can successfully run the following code, which makes me very surprised. Could any of you explain all of this to me?

#! /usr/bin/perl
use a;
a->p();
+7  A: 

As far as I remember "use" perl directive performs checking whether module is already loaded. It's done by calling require() function. So, there is no endless copy.

Pmod
+8  A: 

There are (at least) three different ways of loading something: use, require and do.

use is basically a pimped require and perldoc states for require: require demands that a library file be included if it hasn't already been included. So no problem there.

do is a different story. It executes the file and is more or less like eval or C's #include. Mutual inclusion via do should be fatal.

musiKk
`do` is evil and is best avoided.
Ether
When you goal is to execute an arbitrary file (hey, this is Perl) rather than including it as a package then `do` seems to be the way to go. Maybe it does not really fit in this context; I just remember it that way because _Beginning Perl_ lists `do` in the chapter about modules.
musiKk
If your goal is to execute an arbitrary file, then you may wish to reconsider your design.
daotoad
@daotoad: That's what my remark in parentheses was for. In general you are right.
musiKk
+13  A: 

because the two modules will endlessly copy each other's code to themselves

No, they won't, as you demonstrated with the code that surprised you by working. Perl keeps a record in %INC of which modules have been loaded with use or require and will not attempt to reload them if they get used or required again.

Dave Sherohman