开发者

Including perl modules

I was wondering, do all of the modules I use in a perl script need to be at the beginning of the a script?

The reason I am wonder is I have a place in my script where it "splits" one way is the script connects with SSH using authorized keys. The other way is the script connects with SSH using a username and password. I am using the modules Net::OpenSSH to do SSH. According the cpan doc if I开发者_如何学Go want all username and password authentication I need IO::Pty.

Well I wanted to only check the requirement of IO::Pty if the subroutine set to login with username and password is triggered. Is that possible? To load the module only if a certain subroutine is triggered?


The use IO::Pty; line means the following to Perl:

BEGIN {
    require IO::Pty;
    IO::Pty->import;
}

So first Perl loads the module with require (which will die if it can't find the module), and then it calls the ->import method if it exists.

You can turn this into a runtime conditional as follows:

 if (eval {require IO::Pty}) {
     # IO::Pty->import;
     # or use fully qualified names: IO::Pty::some_sub(...);
     # in both cases, the parenthesis after the subroutine are required, since
     # the import is not visible at compile time
 } else {
     # run other code, or throw an error with `die`
 }

Packages import into other packages, not into other scopes, so the import will be visible outside of the subroutine that performs it. It is probably best to skip the import all together and just use fully qualified names.


If you only want to load a module sometimes then you can use require and eval to check whether you have it:

$haveit = eval "require Foo::Bar";
if ($haveit) {
   # do something
}

The 'use' routine actually does two things:

require Foo::Bar;
import Foo::Bar;

The thing is that 'use' does this at the beginning of the execution, not in a conditional place. So don't use 'use' if you want to only load a module "sometimes" and instead use require and import where you actually want to.

*Edited to include: *

I should have referenced the perl 'use' documentation that explains this very well.

use Module;

is equivalent to:

BEGIN { require Module; Module->import( LIST ); }

And it's the "BEGIN" part that causes it to be loaded no matter where it is in the script, even in another if() clause.


Also take a look at Module::Load.


You don't need to load IO::Pty yourself, Net::OpenSSH will load it when required.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜