How can I conditionally import a package in Perl?

前端 未结 4 2022
死守一世寂寞
死守一世寂寞 2021-01-21 09:53

I have a Perl script which uses a not-so-common module, and I want it to be usable without that module being installed, although with limited functionality. Is it possible?

相关标签:
4条回答
  • 2021-01-21 10:31

    I recommend employing Module::Load so that the intention is made clear.

    Edit: disregard the comments, Module::Load is in core.

    0 讨论(0)
  • 2021-01-21 10:35

    Another approach is to use Class::MOP's load_class method. You can use it like:

    Class::MOP::load_class( 'foobar', $some_options )

    It throws an exception so you'll have to catch that. More info here.

    Also, while this isn't necessarily on every system Class::MOP is awfully useful to have and with Moose becoming more prevalent every day it likely is on your system.

    0 讨论(0)
  • 2021-01-21 10:42

    Consider the if pragma.

    use if CONDITION, MODULE => ARGUMENTS;
    
    0 讨论(0)
  • You can use require to load modules at runtime, and eval to trap possible exceptions:

    eval {
        require Foobar;
        Foobar->import();
    };  
    if ($@) {
        warn "Error including Foobar: $@";
    }
    

    See also perldoc use.

    0 讨论(0)
提交回复
热议问题