dannyd has asked for the wisdom of the Perl Monks concerning the following question:

Good Evening experts,

I have a pretty simple question, but have not been able to find a solution, me being a newbie and all:(

I have a script that needs to be run on a windows machine and a Linux machine(without code changes).

I finished the part for windows, but I have the statement use Win32::EventLog; at the top of the code, and I get a compilation error when I run the script in Linux.

This is what I've tried to do to fix it,

#!/usr/bin/perl -w my $OsDep = 'File::Copy'; if ($^O =~ /MSWin/i) { $OsDep = "Win32\:\:EventLog"; } elsif ($^O =~ /Linux/i) { $OsDep = "File\:\:Copy"; } else { print "Please check documentation for Supported Operating Syst +ems.\n"; } use $OsDep;

Once again please help me.

Replies are listed 'Best First'.
Re: Common use statements for windows and Linux
by Corion (Patriarch) on Jan 18, 2011 at 12:53 UTC

    See use and require.

    Basically, use is compile-time and will happen before you assign any variables, so use $OsDep will not work. I would rewrite the code to:

    if (...) { require Win32::EventLog; Win32::EventLog->import(); } elsif (...) { require File::Copy; File::Copy->import(); } else { warn "Unknown OS $^O detected, using default module(s)."; require File::Copy; File::Copy->import(); };
Re: Common use statements for windows and Linux
by cdarke (Prior) on Jan 18, 2011 at 12:58 UTC
    Or use (no pun intended) the if pragma, for example:
    use if ($^O eq 'MSWin32'), 'Win32::Process'; use if ($^O ne 'MSWin32'), 'POSIX'; use if ($^O ne 'MSWin32'), 'POSIX' => ':sys_wait_h'; # Hack to allow compilation under UNIX # (NORMAL_PRIORITY_CLASS is Win32 only) use if ($^O ne 'MSWin32'), 'constant' => 'NORMAL_PRIORITY_CLASS';
    (from one of my modules which runs child processes on Windows and Linux)
Re: Common use statements for windows and Linux
by tilly (Archbishop) on Jan 18, 2011 at 14:27 UTC
    And yet another solution that I've used is to create a Win32::EventLog module that I can install on Linux.

    This is particularly useful if you need to port working scripts from one to the other. If you can implement the functionality that you need, porting becomes much easier.