tags:

views:

152

answers:

3

What is the best way to programatically determine if a Perl script is executing on a Windows based system (Win9x, WinXP, Vista, Win7, etc.)?

Fill in the blanks here:

my $running_under_windows = ... ? 1 : 0;
+10  A: 

From perldoc perlvar:

  • $OSNAME
  • $^O

The name of the operating system under which this copy of Perl was built, as determined during the configuration process. The value is identical to $Config{'osname'}. See also Config and the -V command-line switch documented in perlrun.

In Windows platforms, $^O is not very helpful: since it is always MSWin32 , it doesn't tell the difference between 95/98/ME/NT/2000/XP/CE/.NET. Use Win32::GetOSName() or Win32::GetOSVersion() (see Win32 and perlport) to distinguish between the variants.

Chris Lutz
Excellent! Thanks!
knorv
What about Cygwin? $^O = 'cygwin'
mobrule
@mobrule - If we're using Cygwin, does it matter? I don't have a Windows box to test it out on, but if you're using Cygwin you basically get the best of both words (for the most part) so it really shouldn't matter. If you want to know how Cygwin affects `$^O` you should run Perl under Cygwin and find out.
Chris Lutz
It depends on what the motivation is for identifying Windows. Maybe knorv is working around some limitation of Windows, or maybe he is taking advantage of some feature available only in Windows.
mobrule
mobrule: $^O eq 'MSWin32' under Cygwin.
knorv
You don't have to think about the details because David Cantrell already did that for you in Devel::CheckOS.
brian d foy
+2  A: 
$^O eq 'MSWin32'

(Source: The perlvar manpage)

hillu
+2  A: 

Use Devel::CheckOS. It handles all of the logic and special cases for you. I usually do something like:

use Devel::CheckOS qw(die_unsupported os_is);

die "You need Windows to run this program!" unless os_is('MicrosoftWindows');

The 'MicrosoftWindows' families knows about things such as Cygwin, so if you are on Windows but not at the cmd prompt, os_is() will still give you the right answer.

brian d foy