Perl: Conditionally load a module

I am using Data::Dump which has a drop in replacement named Data::Dump::Color. I wanted to conditionally/programmatically load a specific module.

if ($color) {
    use Data::Dump::Color;
} else {
    use Data::Dump;
}

This doesn't work because use statements are run before ANY other code is run. The above code will load BOTH modules, because use always runs. Instead you have to use require.

if ($color) {
    require Data::Dump::Color;
    Data::Dump::Color->import();
} else {
    require Data::Dump;
    Data::Dump->import();
}

Calling require does not automatically import all the exported functions, so you have to specifically call the include() function.

Leave A Reply - 2 Replies
Replies
Steven Haryanto 2013-10-18 03:24am - stevenharyanto@... - Logged IP: 203.130.198.32

You probably meant import(), not include().

Steven Haryanto 2013-10-18 03:34am - stevenharyanto@... - Logged IP: 203.130.198.32

You can also disable Data::Dump::Color's color, so:

use Data::Dump::Color;
$Data::Dump::Color::COLOR = $color;

Another example:

use Data::Dump::Color;
$Data::Dump::Color::COLOR = (-t STDOUT); # only use color if we are called interactively
All content licensed under the Creative Commons License