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

Hello,

Some of the scripts I'm writing depend on the hardware I have connected for some testing purposes.

Is there a way to have modules included according to a value of a variable?

my $IS_MULTI_ICE_PRESENT = 1; my $IS_I2C_PRESENT = 0; ... use MyUtils:;MultiICE if ($IS_MULTI_ICE_PRESENT); use MyUtils:;I2C if ($IS_I2C_PRESENT); ...

I know that use is a pragma, therefore this code will not work.

What I want to do is like in "C":

#define IS_MULTI_ICE_PRESENT 1 #define IS_I2C_PRESENT 0 ... #if IS_MULTI_ICE_PRESENT #include "multi_ice.h" #endif #if IS_I2C_PRESENT #include "i2c.h" #endif ...

Is this possible in Perl? (I guess that yes, but I don't know how to ... yet..)

Replies are listed 'Best First'.
Re: [Q]: How to include modules conditionally (using the pragma 'use')?
by cdarke (Prior) on Mar 08, 2010 at 11:44 UTC
    Here is an example of using the if pragma:
    use strict; 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';
Re: [Q]: How to include modules conditionally (using the pragma 'use')?
by Corion (Patriarch) on Mar 08, 2010 at 09:12 UTC

    See use, or if, if you want something more fancy.

Re: [Q]: How to include modules conditionally (using the pragma 'use')?
by WizardOfUz (Friar) on Mar 08, 2010 at 09:11 UTC
    BEGIN { my $LOAD_FOO = 1; eval "use Foo; 1;" or die $@ if $LOAD_FOO; }