From perldoc -f require:
If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.

In other words, if you try this:

require Foo::Bar; # a splendid bareword
The require function will actually look for the "Foo/Bar.pm" file in the directories specified in the @INC array.

But if you try this:

$class = 'Foo::Bar'; require $class; # $class is not a bareword #or require "Foo::Bar"; # not a bareword because of the ""
The require function will look for the "Foo::Bar" file in the @INC array and will complain about not finding "Foo::Bar" there. In this case you can do:
eval "require $class";
...
Having been bitten by this in some code that needs to require the module based on a run time value (solved the problem with an eval), I wonder what the underlying reasons are for not applying the same rules for a scalar string as for a bareword.

Is it

How much code would break if this were made consistent? (not much as far as I can think of)

I also notice that use similarly insists on a bareword.

--
I'm Not Just Another Perl Hacker

Replies are listed 'Best First'.
Re: Passing a run time string to require
by Corion (Patriarch) on Oct 22, 2004 at 17:10 UTC

    There is a hack that makes "require" work almost natural, although it doesn't reraise fatal errors - UNIVERSAL::require. It makes "require" a method that can be called on any scalar, which is quite convenient if you need to dynamically load modules:

    my $module = __PACKAGE__ . "::Plugin\::$class"; if (! $module->require) { warn "$module didn't return a true value:"; croak $@; };

    Of course, depending on your actual needs, maybe one of the Plugin modules already does what you want...

      You're right, it is a hack. It's probably useable in tests and standalone scripts. But this is for a CPAN module. I don't want to rely on someone using my module not having an autoloaded method called require. C'est la vie :|.

      Admittedly, a plug-in is pretty close to what I am doing, but in this case, not a plug-in to an existing module (which a CPAN search gives); this is one of my modules. However, the generic modules, such as Module::Pluggable, seem overkill for what I am doing at present.

      --
      I'm Not Just Another Perl Hacker

        You're right, it is a hack. It's probably useable in tests and standalone scripts. But this is for a CPAN module. I don't want to rely on someone using my module not having an autoloaded method called require. C'est la vie :|.
        UNIVERSAL::require( $scalar )
Re: Passing a run time string to require
by Anonymous Monk on Oct 22, 2004 at 15:39 UTC
    If scalars were treated as bare words, how would you require files that don't end in ".pm", or that contain "::"? You wouldn't want Perl to enforce arbitrary limits on you, now would you?