Search code examples
linuxwindowsperlmoduleperl-module

How do I assure that a module is loaded only if the script is running on Windows?


I have a Perl script that needs to run on both Windows and Linux. The problem is I need to use a Perl module that only applies to Windows.

I have tried the below, but it still includes thie WindowsStuff package.

use strict;
if ($^O eq 'MSWin32' ){
    use My::WindowsStuff;
}
use File::Basename;
use Getopt::Long;
...
...

Solution

  • Because use takes effect at compile time, it doesn't respect the ordinary flow control of the code being compiled. In particular, putting a use inside the false branch of a conditional doesn't prevent it from being processed.

    What you can do?

    a) require import (run-time):

    if( $^O eq 'MSWin32' ) {
       require My::WindowsStuff;
       My::WindowsStuff->import if My::WindowsStuff->can("import");
    }
    

    b) use if (compile-time):

    use if $^O eq 'MSWin32', "My::WindowsStuff";