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

I have an internal module that I include in all my scripts. I have been treating it as an optional dependency by loading it like so BEGIN { eval { require Internal::Module } }. This allows me to share my scripts and not have to worry about the internal module not existing on the users' system. But now I'm thinking it would be easier to manage by removing the extra boilerplate and including the module via the env var like so: export PERL5OPT="-MInternal::Module". This only works if the module exists, but I also need it to work if it does not exist. I've been playing around with the if module but haven't been able to get it to work for this case. Is it possible to do what I want?

Replies are listed 'Best First'.
Re: Is it possible load optional modules from PERL5OPT?
by jo37 (Curate) on Aug 17, 2025 at 10:59 UTC

    You can specify an arbitrary block on the command line with a Maori farewell like this:

    perl -M'5;BEGIN{eval{require Internal::Module}}'

    It is a little bit tricky to embed this in PERL5OPT but maybe it is something you are looking for.

    $ PERL5OPT="-M5;BEGIN{eval{require(Internal::Module)}}" perl -MO=Depar +se -e0 sub BEGIN { require 5; () } sub BEGIN { eval { do { require Internal::Module } }; } '???'; -e syntax OK

    Greetings,
    🐻

    $gryYup$d0ylprbpriprrYpkJl2xyl~rzg??P~5lp2hyl0p$
      Thank you, this is exactly what I was looking for!
Re: Is it possible load optional modules from PERL5OPT?
by haukex (Archbishop) on Aug 17, 2025 at 07:50 UTC

    If you're comfortable building your own Perl, perhaps you're looking for sitecustomize.pl. However, this sounds like it may also be an X/Y Problem - what does your internal module do?

      > However, this sounds like it may also be an X/Y Problem - what does your internal module do?

      I can't know what the OP is trying to achieve but I'm intrigued by this approach.

      One can actually have a general DEV environment where special test and debugging modules are activated by default without polluting the PROD environment with extra code.

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      see Wikisyntax for the Monastery

Re: Is it possible load optional modules from PERL5OPT?
by ysth (Canon) on Aug 17, 2025 at 15:53 UTC
    Easiest just to change your export to test whether to set PERL5OPT:
    if `perl -MInternal::Module -e0 2>/dev/null`; then export PERL5OPT +=-MInternal::Module; fi
    Though possibly you want PERL5OPT="-MInternal::Module $PERL5OPT" in case the env var is being used for something else too?