http://www.perlmonks.org?node_id=751734

gokuraku has asked for the wisdom of the Perl Monks concerning the following question:

Sometimes I write scripts for Unix and Windows, since some tasks run the same on both, occasionally I have something simple that I want to run on both but have library dependencies that cause issues. Case in point now is I have a script that does some clean up by removing directories and on Windows does some registry removal. Ideally it would be nice to have the same script and use Win32::TieRegistry, but I have no found a good example or method of having use load a library depending on platform.

Using an if ($^O =~ /Win32/) { use Win32::TieRegistry } did not give me the right results, it seems to want to load this even before going through the if statement. I'm just curious if this is possible, if its been done or if I am barking up a tree with no cat inside.

Thanks.

Replies are listed 'Best First'.
Re: Mulit-Platform use case
by cdarke (Prior) on Mar 19, 2009 at 14:42 UTC
    Use the 'if' pragma. For example:
    use if ($^O eq 'MSWin32'), 'Win32::Process'; use if ($^O ne 'MSWin32'), 'POSIX'; use if ($^O ne 'MSWin32'), 'POSIX' => ':sys_wait_h'; # Hack to allow compilation under UNIX # (NORMAL_PRIORITY_CLASS is Win32 only) use if ($^O ne 'MSWin32'), 'constant' => 'NORMAL_PRIORITY_CLASS
Re: Mulit-Platform use case
by moritz (Cardinal) on Mar 19, 2009 at 14:34 UTC
    use happens at compile time, so it's independent of any run time condition. The run time version version of use Foo qw(bar baz); is
    require Foo; Foo->import(qw(bar baz));
Re: Mulit-Platform use case
by RyuMaou (Deacon) on Mar 19, 2009 at 19:30 UTC
    About two four years ago (wow, the time flies!), I was messing around with a script I wanted to run on a bunch of different systems, so I was doing a lot of OS detection. I just modified that slightly to check the code and the following syntax worked just fine:

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

    I'll throw the rest of the OS detection craziness into my scratchpad, if anyone is interested in it.
      That will not work stand-alone because (as moritz said) use is executed at compile time. Even if placed in a BEGIN block.
      For example, on Windows:
      use strict; use warnings; if ($^O ne "MSWin32") { use POSIX; } local $, = "\n"; print keys %INC
      shows that POSIX.pm is loaded.