in reply to Controlling "use" statements

Yes, but you don't want to use "use" to do it, because it acts at compile time (it has an implicit BEGIN wrapped around it already). On the other hand requre acts at runtime, which means it can be used to conditionally load modules as needed. If you want it to behave like use, though, you also need to call import on the module, right after doing a require.

There's a gotcha to require semantics though, it requires a "bareword", which is fine if you want to do something like this:

if ($DEBUG) { require Data::Dumper; import Data::Dumper; }

But if you want to put the module names in variables, then you'll probably need something like this:

my @debug_modules = qw( Data::Dumper CGI Test::Deep ); foreach my $mod (@debug_modules) { eval "require $mod"; import $mod; }
(Note, some folks are down on eval STRING, but this is a case where it's necessary.)

If you want to read up on this, look into things like "perlmod", and the "use" and "require" sections of "perlfunc". Do not however, waste your time looking for "import" in perlfunc. It's not a "function", it's more like a reserved name for a subroutine.

Replies are listed 'Best First'.
Re^2: Controlling "use" statements
by nodice (Initiate) on Jun 13, 2007 at 19:25 UTC

    Thank you, this is very useful. As a followup, what would be the correct way to include certain features with the module?

    For example, I want the equivalent of

    use CGI::Carp qw(fatalsToBrowser set_message)

    I know that

    require CGI::Carp qw(...)

    won't work, because it can only handle barewords. What is the correct way to do this?

    Thanks.
      use CGI::Carp qw(fatalsToBrowser set_message)

      is a shortcut for

      BEGIN { require CGI::Carp; import CGI::Carp qw(fatalsToBrowser set_message); }

      You can easily add an if in there.

      BEGIN { if ($DEBUG) { require CGI::Carp; import CGI::Carp qw(fatalsToBrowser set_message); } }
      BEGIN { use vars qw($devel); $devel = 0; # production } BEGIN { my @args = $devel ? qw(fatalsToBrowser set_message) : (); require CGI::Carp; CGI::Carp->import(@args); }

      The equivalent of use Module LIST is BEGIN { require Module; Module->import(LIST) }.

      --shmem

      _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                    /\_¯/(q    /
      ----------------------------  \__(m.====·.(_("always off the crowd"))."·
      ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re^2: Controlling "use" statements
by ysth (Canon) on Jun 14, 2007 at 23:05 UTC
    Do not however, waste your time looking for "import" in perlfunc. It's not a "function", it's more like a reserved name for a subroutine.
    But there is a perlfunc entry for it, just in case you do look.