Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Using perl module if env is enabled

by haukex (Bishop)
on Dec 09, 2019 at 15:24 UTC ( #11109882=note: print w/replies, xml ) Need Help??


in reply to Using perl module if env is enabled

In my experience, conditionally loading a module (like Corion and tobyink already showed) isn't always the only thing going on, since later on in your code you might want to use functions from that module conditionally, based on whether it was loaded in the first place. Personally, I prefer to set a global variable, something like this:

our $HAVE_XYZ; BEGIN { $HAVE_XYZ = !!$ENV{USE_XYZ} } use if $HAVE_XYZ, 'XYZ'; ... if ( $HAVE_XYZ ) { XYZ::foo(...) }

Also, note that BEGIN is uppercase, not begin {...}.

Replies are listed 'Best First'.
Re^2: Using perl module if env is enabled
by tobyink (Canon) on Dec 09, 2019 at 16:07 UTC

    A constant is usually better than a variable:

    use constant HAVE_XYZ => !!$ENV{USE_XYZ}; use if HAVE_XYZ, 'XYZ'; ... if ( HAVE_XYZ ) { XYZ::foo(...) }

    At it means that the if (...) stuff will be optimized away entirely when it's false. Also it will protect against $HAVE_XYZ being accidentally changed half way through running the process. (Of course, sometimes you do wish to start using XYZ later on by changing the variable, but that's probably less common.)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (10)
As of 2020-08-05 17:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which rocket would you take to Mars?










    Results (36 votes). Check out past polls.

    Notices?