How do I conditionally use a Perl module only if I'm on Windows?

后端 未结 4 752
醉话见心
醉话见心 2021-02-14 22:43

The following Perl code ..

if ($^O eq \"MSWin32\") {
  use Win32;                                                                                                         


        
相关标签:
4条回答
  • 2021-02-14 23:15

    This code will work in all situations, and also performs the load at compile-time, as other modules you are building might depend on it:

    BEGIN {
        if ($^O eq "MSWin32")
        {
            require Module;
            Module->import();  # assuming you would not be passing arguments to "use Module"
        }
    }
    

    This is because use Module (qw(foo bar)) is equivalent to BEGIN { require Module; Module->import( qw(foo bar) ); } as described in perldoc -f use.

    (EDIT, a few years later...)

    This is even better though:

    use if $^O eq "MSWin32", Module;
    

    Read more about the if pragma here.

    0 讨论(0)
  • 2021-02-14 23:21

    require Module;

    But use also calls import, require does not. So, if the module exports to the default namespace, you should also call

    import Module qw(stuff_to_import);

    You can also eval "use Module" - which works great IF perl can find the proper path at runtime.

    0 讨论(0)
  • 2021-02-14 23:25

    In general, use Module or use Module LIST are evaluated at compile time no matter where they appear in the code. The runtime equivalent is

    require Module;
    Module->import(LIST)
    
    0 讨论(0)
  • 2021-02-14 23:29

    As a shortcut for the sequence:

    BEGIN {
        if ($^O eq "MSWin32")
        {
            require Win32;
            Win32::->import();  # or ...->import( your-args ); if you passed import arguments to use Win32
        }
    }
    

    you can use the if pragma:

    use if $^O eq "MSWin32", "Win32";  # or ..."Win32", your-args;
    
    0 讨论(0)
提交回复
热议问题