A short time ago, someone asked how to use a module that wasn't in its own file but was coded directly into a single-file project. The answer: call import directly, probably from a BEGIN block, assuming it's necessary to do anything at all.

I noticed the question because I'd just started some testing code for Exporter::VA, and originally thought of having a bunch of small dummy modules in one test file along with the main-line code that uses them. But I decided against tricks because I wanted the test to look just like the typical use.

But now I have an idea. How about a very simple pragmatic module that just tells perl that a module is already loaded? Then a subsequent use will just import. You don't have to worry about how to adapt a particular module for being included in-line, or have funny constructs in your code. This would be handy for testing, for "linking" some code together into one file, and for having a .pm file suply helper modules directly in the same file.

I'm thinking of something like:

use pm_present;
tells perl that the current __PACKAGE__ is "loaded". That is, add $INC{__PACKAGE__} ||= $0.

use pm_present Module;
tells perl that the specified Module is "loaded". That is, add $INC{Module} ||= $0.

use pm_present Module => filename
tells perl to use the specified name for the entry in the %INC hash instead of the current source file name.

In the spirit of use lib, I think this will be just a couple lines long.

What do y'all think? The name is open to suggestions.

—John

Replies are listed 'Best First'.
Re: pragmatic module idea
by chromatic (Archbishop) on Dec 16, 2002 at 20:39 UTC

    I think it's kind of silly to write a module to save people having to write one line of code. It's not a particularly difficult line of code, either.

      Well, we have prior art:

      lib, base, and File::Slurp. I remember when overload wasn't a pragma but you had to update the hash yourself. For that matter, isn't strict just changing one variable?

      —John

        You're right about strict, because it's encapsulating non-obvious behavior, but I don't use lib, base, or File::Slurp. (The pragmas are less defendable on the same idea, but File::Slurp has crossed a line of encapsulation.)

        If you think it's necessary to write a module to encapsulate an assignment to %INC, go ahead. I think it's of dubious value -- of the times I needed to fake a module, I had to do several other things at the same time.

        My instinct is to say that the type of people who would need this module already know how to do what it does and are likely to do it themselves.