Jean
Jean

Reputation: 22675

Perl library usage

Is there any benefit (w.r.t performance/memory usage) in including use mylibrary conditionally (assuming mylibrary is used only if condition is true) compared to adding use mylibrary on top of the script unconditionally?

# Script 1 (Unconditional use)
use mylibrary;
if($condition)
{
    # Do something with mylibrary
}

# Script 2 (Conditional use)
if($condition)
{
    use mylibrary;
    # Do something with mylibrary
}

Upvotes: 4

Views: 133

Answers (2)

Ether
Ether

Reputation: 53966

You can achieve conditional loading, including the side benefits of the use (the calling of ->import, and execution at compilation time) with the if pragma: http://perldoc.perl.org/if.html

use if $Config{usethreads}, 'Library::Requiring::Threads';

One caveat, of course, is that the if expression is executed at compile time, so everything it depends on must also be known and available at compile time.

Upvotes: 0

Sean
Sean

Reputation: 29772

use is a compile-time construct. In your two cases, mylibrary is actually being imported in both of your "Unconditional" and "Conditional" cases. If you want to import a library conditionally, use require, a run-time construct, instead.

if ($condition) {
    require mylibrary;
    # mylibrary->import;
    # ...
}

In such a case you lose some of the compile-time benefits of use. For example, require does not call mylibrary->import at compile time, as use does. You can call import yourself if you want, as I show above, but anything import does that has an effect at compile time will not have that effect when called at run time.

Suppose your module mylibrary exports a function foo. Then this works:

use strict;
use mylibrary;  # exports function foo()
foo;

But this is an error:

use strict;
require mylibrary;
mylibrary->import; # too late to notify Perl's parser about the foo() function
foo; # error; unknown function

As to whether there's any benefit to doing so, there can be if mylibrary is expensive to import. Most of the time, probably not.

Upvotes: 7

Related Questions