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

Hi,

I'm porting my freeBSD code to Win32 and need to use a different ::SerialPort module depending on the platform

This doesn't work...

$platform = "win32";    # I really test $^O

if ($platform eq "win32") {
use Win32::SerialPort;
} else {
use Device::SerialPort;
}

Perl looks for both of them and fails with a "can't find".

What's the right way to do this?

Thanks, Dave

Replies are listed 'Best First'.
Re: conditional USE MODULE
by BrowserUk (Patriarch) on Oct 18, 2011 at 04:40 UTC

    Use the pragma module if:

    use if $^O eq 'MSWin32', 'Win32::SerialPort'; use if $^O ne 'MSWin32', 'Device::SerialPort';

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: conditional USE MODULE
by ikegami (Patriarch) on Oct 18, 2011 at 06:26 UTC

    Some possibilities:

    use if $^O eq 'MSWin32', 'Win32::SerialPort'; use if $^O ne 'MSWin32', 'Device::SerialPort';
    use if 1, $^O eq 'MSWin32 ? 'Win32::SerialPort' : 'Device::SerialPort';
    BEGIN { eval( $^O eq 'MSWin32 ? 'use Win32::SerialPort; 1' : 'use Device::SerialPort; 1' ) or die $@; }
Re: conditional USE MODULE
by Khen1950fx (Canon) on Oct 18, 2011 at 03:29 UTC
    In order to use a conditional use, you'll need to place your code in a BEGIN block with a couple of evals. It's relatively easy:
    #!/usr/bin/perl -l use strict; use warnings; BEGIN { my $OS_win = ($^O eq "MSWin32") ? 1 : 0; print "Perl version: $]"; print "OS version: $^O"; if ($OS_win) { print "Loading Windows modules"; eval "use Win32::SerialPort"; die "$@" if $@; } else { print "Loading Unix modules"; eval "use Device::SerialPort"; die "$@" if $@; } }
Re: conditional USE MODULE
by hennesse (Beadle) on Oct 18, 2011 at 13:29 UTC

    Thank you, everyone

    I woke up this morning thinking the answer would have something to do with a BEGIN block. It's amazing how much Perl (or anything) you can write and never have the opportunity to use (or understand) some elementary things

    I ended up using a BEGIN somewhere in-between Khen1950fx and ikegami's suggestions.

    bikeNomad's "Platform-independent Serial Port code" is quite clever, and I would have used it, but I intend to distribute my (Electronic Beer Brewery) code, and the less "things" there are, the less things that can go wrong down the road.

    Thanks monks!

    Dave
Re: conditional USE MODULE
by Anonymous Monk on Oct 18, 2011 at 08:38 UTC