Identifying the OS in a Perl script

Colin Watson cjwatson at ubuntu.com
Thu Sep 1 16:00:48 UTC 2005


On Thu, Sep 01, 2005 at 11:24:11AM -0400, Stephen R Laniel wrote:
> I'm writing a Perl script that I'll need to be portable
> across OSes. This is Perl's great virtue, of course. But
> it's going to be running under cygwin when in Windows, and
> I'll need some paths in there to be different: I'll need it
> to save to c:\Documents and Settings\Username\foo, for
> instance, whereas under Linux and OS X I'll need it to
> save in ~foo.
> 
> So what I'd like is to be able to do something like so in
> the script:
> 
> my $path = '';
> if( $someVar == "Windows" ) {

Use $^O (see perlvar(1)).

You may also find a number of Perl's standard modules (particularly
File::*) useful when doing portable file name manipulation.

> Likewise, under cygwin the Perl interpreter is stored in
> c:\cygwin\bin\perl.exe, which is /bin/perl.exe; under Linux,
> it's stored in /usr/bin/perl. So is there any way to have a
> platform-specific "shebang" line, e.g.,
> 
> if( $someVar == "cygwin" ) {
> 	#!/bin/perl.exe
> }
> elsif( $someVar == "Linux" ) {
> 	#!/usr/bin/perl
> }

The shebang line is read by the kernel, so you can't surround it by code
or anything like that. As a last resort you can always write a Makefile
to preprocess the program at build-time and fill in the appropriate
shebang line.

Alternatively, you could encourage users to create a /usr/bin/perl
symlink?

Cheers,

-- 
Colin Watson                                       [cjwatson at ubuntu.com]




More information about the ubuntu-users mailing list