views:

194

answers:

1

How can I implement lazy module loading in Perl?

I've seen similar things in python and implementation is somewhat simpler, but in Perl I think this would be a bit harder.

+14  A: 

Load module when you want

If you need to load whole module at runtime you use require. But for importing you'll require additional code. Here is example:

## this function is almost the same 
## as "use My::Module qw( :something  )"
sub load_big_module_at_runtime {
    ## load module in runtime
    require My::Module;
    ## do import explicty if you need it
    My::Module->import( ':something' );
}

Load module when its functions are used

You can also use autouse to load module only when its function is used. For example:

## will load module when you call O_EXCL()
use autouse Fcntl => qw( O_EXCL() );

Load function only when it's used

There is also SelfLoader module, which allows you to load single functions only when you need it. Take a look at AutoLoader module which doing nearly the same thing.

I also recommend to read coresponding recipes from Perl Cookbook.

Ivan Nevostruev
The second part of your answer is very interesting. I had no idea that module existed. Thanks!
xyld
Take a look at `SelfLoader` module too.
Ivan Nevostruev
Has anybody used `if` to achieve that?
innaM
`if` is usefull if you need to decide: load or not load module.
Ivan Nevostruev