Reputation: 927
Imagine my script has these two subs
sub with_json_mod{
use JSON::Tiny;
blah blah blah;
}
sub without_json_mod{
blah blah blah;
}
I only want to use without_json_mod
when JSON::Tiny
is not installed.
How can I make Perl not fail if JSON::Tiny
is not installed and, instead, use the without_json_mod
sub instead?
I tried to call require
in the with_json_mod
and it seems to work, but it doesn't work when I try to make it import the encode_json
sub as in
sub with_json_mod{
require JSON::Tiny qw/encode_json/;
blah blah blah;
}
Upvotes: 1
Views: 511
Reputation: 69224
There are two main differences between use
and require
.
use
happens at compile time and require
happens at runtime.use
calls the import()
method in the loaded package (if one exists) and require
doesn't.So you need to add a call to import()
.
sub with_json_mod{
require JSON::Tiny;
JSON::Tiny->import('encode_json');
blah blah blah;
}
Upvotes: 6
Reputation: 53478
That's because you're calling require
incorrectly.
What you need is:
require JSON::Tiny;
JSON::Tiny -> import ( 'encode_json' );
You can wrap that in an 'eval' too, and test the value of $@
:
eval { require JSON::Tiny; };
warn $@ if $@;
Upvotes: 8