devnul has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

I am greatly simplifying the description of this problem. I believe the best solution would be to fix the "old code", but there is so much of it that this is not feasible.

I have 2 packages:

packageA.pm:
package PackageA; require "libraries/somelib.pl"; ... variables, functions, etc 1;
packageB.pm:

package PackageB; require "libraries/somelib.pl"; #NOTE: Same library as included in pac +kageA ... variables, functions, etc 1;
.. Now I want to use both of these packages in a script:
#!/usr/bin/perl -w use strict; use PackageA; use PackageB;
The problem is that the require in packageB never got executed. None of the functions or variables in somelib.pl exist within that namespace. Is there some reasonable solution to this problem? Again, I feel compelled to mention that the problem is far bigger then this small example I have show here. If the real world were this small I would just change somelib.pl into a module or something appropriate along those lines.

I have tried using "do"s, but unfortunately many of these libraries "require" other libraries which creates a situation where adding a "do" to one package can actually break another package because although the "do" is executed, none of the requires within the "done" file are..

I hope this makes sense!

- Greg

Replies are listed 'Best First'.
Re: Perl use and require enigma
by etcshadow (Priest) on Jun 16, 2004 at 23:21 UTC
    The short answer: you should be doing "libraries/somelib.pl" rather than requireing it. Reading over the docs for do (specifically, do EXPR, not do BLOCK... they are (sadly) not very closely related) and require would probably be a good idea, but the executive summary is: require will only execute it the first time it is seen in a perl process (because the expectation with require and use is that the file is a "package" or "module" and things are either exported or referred to by namespace... they don't have to be defined anew in each require-er).

    Of course, you could also go the better route, and turn "libraries/somelib.pl" into a real module, and use it... but that will be more work (probably worth it, though).

    ------------ :Wq Not an editor command: Wq
Re: Perl use and require enigma
by Sidhekin (Priest) on Jun 16, 2004 at 22:21 UTC

    Definitely a better idea to fix the old code, but ... would something like this DWYW?

    #!/usr/bin/perl -w use strict; BEGIN { local %INC = %INC; require PackageA; import PackageA if UNIVERSAL::can('PackageA', 'import'); } BEGIN { local %INC = %INC; require PackageB; import PackageB if UNIVERSAL::can('PackageB', 'import'); }

    print "Just another Perl ${\(trickster and hacker)},"
    The Sidhekin proves Sidhe did it!