in reply to Use a module only if it is in use

Why?

Check %INC to see if a module was loaded.

Update: Fixed markup

Replies are listed 'Best First'.
Re^2: Use module only if it is in use
by vitoco (Hermit) on Sep 02, 2009 at 14:50 UTC

    It was that simple!!!

    M::hello("again") if $INC{"M.pm"};

    Is it safe to asume that double colons in module names get always translated into slashes ("::" -> "/") instead of backslashes or whatever is used by the OS for subdirs?

      Is it safe to asume that double colons in module names get always translated into slashes ("::" -> "/") instead of backslashes or whatever is used by the OS for subdirs?
      No, it's not safe to assume that. And be lucky. Your code wouldn't work if Perl changed the '::' to a '/', because that it would try to divide M by hello("again"), which most likely results in an error.

      Perl maps '::' to the appropriate directory separator when it's used as a bareword argument to use and require. But that isn't always.

        Is it safe to asume that double colons in module names get always translated into slashes ("::" -> "/") instead of backslashes or whatever is used by the OS for subdirs?
        No, it's not safe to assume that.

        IMO it is safe to assume that for checking %INC. It always worked on MacPerl, on the pre OSX Macintosh, where the system's path separator is a ":". It most definitely is safe on Windows perls, too. If there are exceptions, I haven't heard of them, yet.

        He was asking if the keys of %INC use / instead of :: across all systems, and the answer is yes.

        I meant as a key for %INC, not as barewords:

        $text = Text::Unidecode::unidecode($text) if $INC{"Text/Unidecode.pm"};
      Yes, but again, why? I can't think of a scenario where this would possibly be useful. It feels like you're testing for a side-effect of the problem, and not for the problem itself.

        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.