Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Greetings monks. In an attempt to speed up a bit of code, I read somewhere about the existience of a method which does not load a module when a script is started, but loads them up only if called. Does someone know of this? Regards, Stacy.

Replies are listed 'Best First'.
Re: Load only if needed
by merlyn (Sage) on May 28, 2001 at 10:33 UTC
(ar0n: require) Re: Load only if needed
by ar0n (Priest) on May 28, 2001 at 05:44 UTC
    require

    ar0n - drunk ]


    update -- the morning after: ehhh, what tye said...

      One thing that my drunk friend failed to mention, is that you have to write your code such that the require doesn't get run unless you need the module. For example, this code:

      require Magic::SuperAndSpiffy::ButSlow; sub neatTrick { # ... }
      isn't going to help your problem. But, this code:
      sub neatTrick { require Magic::SuperAndSpiffy::ButSlow; # ... }
      will only load the ButSlow.pm code the first time neatTrick is called.

      Now, if you are currently useing the big module, then things get a bit trickier. First, try chaning your code from: use Magic::SuperAndSpiffy::ButSlow qw( Stuff Junk ); to:

      require Magic::SuperAndSpiffy::ButSlow; Magic::SuperAndSpiffy::ButSlow->import( qw( Stuff Junk ) );
      and see what breaks. Anything that breaks was code that depended on things that were happening at compile time because of your use statement. I think those should mostly be pretty easy to fix. Then you can move the require and import code so that it only gets called when you need it.

      Note, however, that import should only be called once (calling require multiple times doesn't hurt by design). You can also just try leaving out the import and see what breaks and whether you'd just rather fix that instead of figuring out a slick way to call import only once the first time you need it.

              - tye (but my friends call me "Tye")
Re: Load only if needed
by johannz (Hermit) on May 29, 2001 at 22:28 UTC

    Just for fun, 'RE: Factory Pattern for Class Heirarchy', a node I wrote back in October did loading of modules at runtime. It is not as efficient as autouse, but it allowed me to learn how AUTOLOAD and the UNIVERSAL package worked.

    But merlyn is correct in saying to use 'autouse'; it's more correct(read Safer) than my experiment.