Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

module

perl

The following Perl code ..

if ($^O eq "MSWin32") {
  use Win32;                                                                                                                                                                                           
  .. do windows specific stuff ..
}

.. works under Windows, but fails to run under all other platforms ("Can't locate Win32.pm in @INC"). How do I instruct Perl to try import Win32 only when running under Windows, and ignore the import statement under all other platform?

like image 989
knorv Avatar asked Sep 17 '09 22:09

knorv


2 Answers

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.

like image 54
Ether Avatar answered Oct 23 '22 15:10

Ether


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;
like image 31
ysth Avatar answered Oct 23 '22 16:10

ysth