Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re^4: Use module only if it is in use

by vitoco (Friar)
on Sep 02, 2009 at 15:47 UTC ( #792952=note: print w/replies, xml ) Need Help??

in reply to Re^3: Use module only if it is in use
in thread Use a module only if it is in use

I don't want to load helper modules that potentially won't be used.

For example, I have to use unidecode() from Text::Unidecode in the module only if the calling program also uses it. Using that method always have a penalty in performance if data is ASCII only.

You are right if you think that a parameter or something like that should be used, but I want to keep things simple and don't want to force an installation of a non-core module that won't be used.

BTW, I tried some other things like loading the external module from my own only if a parameter is being set in new() (yes, runtime!), but the code become dirty.

Replies are listed 'Best First'.
Re^5: Use module only if it is in use
by ikegami (Pope) on Sep 02, 2009 at 16:13 UTC

    I don't want to load helper modules that potentially won't be used.

    How does not calling the sub you need to call solve that?

    The actual solution is to delay loading the module until you need it.

    sub rarely_called { require Text::Unidecode; return Text::Unidecode::unidecode($_[0]); }

    You can throw in an import in there if you so desire.

    sub rarely_called { require Text::Unidecode; import Text::Unidecode qw( unidecode ); return unidecode($_[0]); }

      Cute alternative:

      sub unidecode { require Text::Unidecode; no warnings 'redefine'; *unidecode = \&Text::Unidecode::unidecode; goto &unidecode; }

      Shouldn't that have a relevant overhead when used as:

      while ($line = <F>) { chomp($line); $line = rarely_called($line) if $asciify; ... }

      BTW, I did something like that (using eval), but checking a flag to require the module only in the first call.

        Benchmark and find out. Or use the self-loading alternative. Or split the initialisation from the actual use.
        require Text::Unidecode if $asciify; while ($line = <F>) { chomp($line); $line = Text::Unidecode::unidecode($line) if $asciify; ... }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://792952]
[Corion]: Test...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (6)
As of 2018-06-23 16:46 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (125 votes). Check out past polls.