Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Conditional loading of module with global exports

by kcott (Archbishop)
on Feb 22, 2016 at 21:22 UTC ( [id://1155849]=note: print w/replies, xml ) Need Help??


in reply to Conditional loading of module with global exports

G'day learnedbyerror,

You can conditionally load modules using the if pragma.

Command line options will be processed at runtime, which will be too late to affect compile-time loading of modules. However, you can modify the command line in a different way, by setting an environment variable, which will be available at compile time.

Here's a minimal example (pm_1155832_cond_use_mod.pl) using List::Util:

#!/usr/bin/env perl -l use strict; use warnings; # Compile time use if $ENV{PM_1155832_USE}, 'List::Util' => qw{max}; BEGIN { print 'Check for List::Util::max() at compile time'; eval { max(1, 2) }; print $@ if $@; } # Runtime if (! $ENV{PM_1155832_USE}) { require List::Util; List::Util->import(qw{max}); } print 'Max is ', max(1, 2);

Load module at runtime:

$ pm_1155832_cond_use_mod.pl Check for List::Util::max() at compile time Undefined subroutine &main::max called at ./pm_1155832_cond_use_mod.pl + line 11. Max is 2

Load module at compile time:

$ PM_1155832_USE=1 pm_1155832_cond_use_mod.pl Check for List::Util::max() at compile time Max is 2

— Ken

Replies are listed 'Best First'.
Re^2: Conditional loading of module with global exports
by learnedbyerror (Monk) on Feb 22, 2016 at 21:34 UTC

    Ken, good catch! I had not thought about using an environment variable. While not my exact preference of handling it via the command line parameters, it does provide a way to handle from the command line.

    I will give this a try!

    lbe

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1155849]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2024-04-23 19:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found