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

Hi i am useing a common perl file on both linux and windoes systems. Based on the value of $ENV{OSTYPE} i want to use Win32::OLE in my script. any way to "use" conditionally to include a module based on the valuse of OSTYPE??

Replies are listed 'Best First'.
Re: conditionally include a module
by FunkyMonk (Bishop) on Aug 23, 2007 at 08:53 UTC
    As well as the require method already mentioned, there's also a standard module for this, if:
    use if ($^O eq 'MSWin32'), 'Win32::OLE';

      standard strictly above 5.6.1

      % steph@apexPDell2 (/home/stephan) % % perl -MModule::CoreList -e 'print Module::CoreList->first_release(q[ +if])' 5.006002
      cheers --stephan
        Standard strictly above 5.7.2 *and* in 5.6.2 :-)
        $ corelist -a if if was first released with perl 5.006002 5.006002 0.03 5.007003 0.01 5.008 0.01 5.008001 0.03 5.008002 0.03 5.008003 0.03 5.008004 0.03 5.008005 0.03 5.008006 0.03 5.008007 0.03 5.008008 0.05 5.009 0.03 5.009001 0.0401 5.009002 0.0401 5.009003 0.05 5.009004 0.05 5.009005 0.05
        Also note that "if was first released with perl 5.006002" is incorrect - it was first released with perl 5.7.3 in March 2002. 5.6.2 was released in November 2003.
Re: conditionally include a module
by GrandFather (Saint) on Aug 23, 2007 at 08:46 UTC

    Probably you want something like:

    if ($^O eq 'MSWin32') { require Win32::OLE; }

    Note that $ENV{OSTYPE} is not cross platform.


    DWIM is Perl's answer to Gödel
      Note that $ENV{OSTYPE} is not cross platform

      Interestingly enough, there's a post just appeared on comp.lang.perl.misc pointing out that $^O is writable (can be modified) - on Windows, at least. I guess if we wanted to dot all of our i's and cross all of our t's we'd have to warn about that, too ... and recommend using $Config::Config{osname} (which actually is readonly) instead.

      Cheers,
      Rob

      Afterthought: Heh ... then again, $Config::Config{osname} can always be modified using tied ....
Re: conditionally include a module
by Corion (Patriarch) on Aug 23, 2007 at 08:48 UTC

    See use:

    It is exactly equivalent to BEGIN { require Module; import Module LIST; }

    So, do just that, except possibly without the BEGIN block, if you want to delay the decision further:

    # use Win32::OLE; # becomes if ($^O eq 'MSWin32') { # dunno about Cygwin require Win32::OLE; Win32::OLE->Option( Warn => 3 ); # to get quicker/better feedback +on errors };

      Just a little note on top of that. The import is what handles arguments you normally pass to use, so if you do something like:

      use Whatever::Module qw(funky);

      you have to add a Whatever::Module->import(qw(funky)); after your require.

Re: conditionally include a module
by ambrus (Abbot) on Aug 23, 2007 at 09:41 UTC

    use if # it's a core module