Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Perl allow mutual "use" relationships between modules?

Tags:

perl

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();
like image 679
Haiyuan Zhang Avatar asked Jun 18 '10 09:06

Haiyuan Zhang


2 Answers

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.

like image 139
Dave Sherohman Avatar answered Oct 19 '22 00:10

Dave Sherohman


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.

like image 9
musiKk Avatar answered Oct 18 '22 22:10

musiKk