Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement lazy module loading in Perl?

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.

like image 268
dlamotte Avatar asked Nov 10 '09 19:11

dlamotte


1 Answers

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.

like image 84
Ivan Nevostruev Avatar answered Oct 14 '22 09:10

Ivan Nevostruev