Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect the operating system in Perl?

I have Perl on Mac, Windows and Ubuntu. How can I tell from within the script which one is which? Thanks in advance.

Edit: I was asked what I am doing. It is a script, part of our cross-platform build system. The script recurses directories and figures out what files to build. Some files are platform-specific, and thus, on Linux I don't want to build the files ending with _win.cpp, etc.

like image 912
mxcl Avatar asked Dec 02 '08 16:12

mxcl


People also ask

What is system() in Perl?

Perl System () Function: What It Does Perl's system() function executes a system shell command. Here the parent process forks a child process, and then waits for the child process to terminate. The command will either succeed or fail returning a value for each situation.

Why we use system in Perl?

The command will be executed just as if you typed it into a shell on your computer. When you use system, the input to the command you're executing (if any) comes from the same input stream as your perl program reads from; similarly, the output of the command (if any) goes to the same output stream as your perl program.


2 Answers

Examine the $^O variable which will contain the name of the operating system:

print "$^O\n"; 

Which prints linux on Linux and MSWin32 on Windows.

You can also refer to this variable by the name $OSNAME if you use the English module:

use English qw' -no_match_vars '; print "$OSNAME\n"; 

According to perlport, $^O will be darwin on Mac OS X.


You can also use the Config core module, which can provide the same information (and a lot more):

use Config;  print "$Config{osname}\n"; print "$Config{archname}\n"; 

Which on my Ubuntu machine prints:

linux i486-linux-gnu-thread-multi 

Note that this information is based on the system that Perl was built, which is not necessarily the system Perl is currently running on (the same is true for $^O and $OSNAME); the OS won't likely be different but some information, like the architecture name, may very well be.

like image 137
Robert Gamble Avatar answered Sep 20 '22 09:09

Robert Gamble


If you need more specific information on Windows this may help.

my $osname = $^O;   if( $osname eq 'MSWin32' ){{   eval { require Win32; } or last;   $osname = Win32::GetOSName();    # work around for historical reasons   $osname = 'WinXP' if $osname =~ /^WinXP/; }} 

Derived from sysinfo.t, which I wrote the original version.

If you need more detailed information:

my ( $osvername, $major, $minor, $id ) = Win32::GetOSVersion(); 
like image 29
Brad Gilbert Avatar answered Sep 18 '22 09:09

Brad Gilbert