Cross Platform Perl

Paul Fenwick pjf at
Wed Oct 16 22:01:33 CDT 2002

G'day Adam,

On Thu, Oct 17, 2002 at 12:42:42PM +1000, Adam Clarke wrote:

> I'm trying to write a script that runs on Linux (Unix) and Win32. I want 
> to /use/ a module when on Win32 (to access the registry) that doesn't 
> exist in Unixy perl. Is there a way to skip a use statement at runtime 
> based on platform or is the only/best way to make a full build 
> (MakeMaker thing) and handle the differences there somehow. If the 
> latter, anyone got some simple pointers.

Glad you asked!  Perl has a variable called $^O (or $OSNAME when
using English) that gives you the name of the operating system
you're running under.

So you can do the following:

BEGIN {		# So we run at the same time as most use statements.
	if ($^O eq 'MSWin32') {
		eval { use My::Module; }

The eval is needed because usually use statements get executed
immediately, regardless of context.  The BEGIN means that your
chunk of code is executed "at compile time".  If this isn't important,
you can leave the BEGIN block out.

There's lots of code out there which does different things depending
upon the OS.  Take a look at File::Copy's source code
(perldoc -m File::Copy) to see a lot of this in action.



Paul Fenwick <pjf at> |
Director of Training                   | Ph:  +61 3 9354 6001
Perl Training Australia                | Fax: +61 3 9354 2681

More information about the Melbourne-pm mailing list