JohnnyLoo
JohnnyLoo

Reputation: 927

Use Perl module only when it is needed within a subroutine

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

Answers (2)

Dave Cross
Dave Cross

Reputation: 69224

There are two main differences between use and require.

  1. use happens at compile time and require happens at runtime.
  2. 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

Sobrique
Sobrique

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

Related Questions