Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
...
...
like image 428
StrongWind Avatar asked Dec 14 '22 20:12

StrongWind


1 Answers

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";
like image 60
Miguel Prz Avatar answered Jan 13 '23 14:01

Miguel Prz