1

A perl script which would include different modules for both Windows and Linux, In order to make it cross-platform, I want someway to implement it, just like in C++:

#if _WIN32
//...
#else
//...
#endif
Baiyan Huang
  • 6,463
  • 8
  • 45
  • 72
  • 1
    see http://stackoverflow.com/questions/334686/how-can-i-detect-the-operating-system-in-perl – Alex Sep 12 '11 at 02:49
  • @Alex I don't see it works: use Win32::Console::ANSI if($^O eq 'MSWin32'); – Baiyan Huang Sep 12 '11 at 02:57
  • 2
    The loading of modules via `use` is done at compile time. You can, however, use Module::Load (http://search.cpan.org/~bingos/Module-Load-0.20/lib/Module/Load.pm), and say something along the lines of `if($^O eq 'MSWin32'){load 'Win32::Console::ANSI'}else{#do something else...or not...whatever}` –  Sep 12 '11 at 03:22
  • 1
    Just a note: remember to use [File::Spec](http://perldoc.perl.org/File/Spec.html) catfile() and catdir() to build file paths and paths in a portable way. – Marco De Lellis Sep 12 '11 at 09:15
  • 1
    @Marco De Lellis, I prefer [Path::Class](http://search.cpan.org/perldoc?Path::Class). It's a wrapper around File::Spec that resolves some issues with File::Spec. Note that Windows does support "/" as a directory seperator (natively!), so one can usually get away without using File::Spec or Path::Class. – ikegami Sep 12 '11 at 16:54

1 Answers1

5

if, $^O:

use if $^O eq 'MSWin32', Win32::Console::ANSI::;

Alternatively,

use Win32::Console::ANSI ();

is equivalent to

BEGIN {
    require Win32::Console::ANSI;
}

so you could also use

BEGIN {
    require Win32::Console::ANSI
        if $^O eq 'MSWin32';
}
cjm
  • 61,471
  • 9
  • 126
  • 175
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • Can't get the `$^O` link to work. It's http:// perldoc.perl.org/perlvar.html#$^O (minus the space) – ikegami Sep 12 '11 at 04:26
  • I can. :-) Try linking to the [English](http://search.cpan.org/perldoc?English) name. – cjm Sep 12 '11 at 05:43
  • @DVK, `use Win32::Console::ANSI ();` is always equivalent to `BEGIN { require Win32::Console::ANSI; }`. It will not call `import` even if it does exist. – ikegami Sep 12 '11 at 15:30
  • @DVK, It would be different if I had said `use Win32::Console::ANSI;`. By the way, `Module->import` does not throw an error even if `import` does not exist. – ikegami Sep 12 '11 at 16:53