Using the Perl Library

Is there any advantage (using / using memory) when switching use mylibraryconditionally (it is assumed that it is mylibraryused only if the condition is true) compared to adding use mylibraryover 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
}
+4
source share
2 answers

useis a compile time construct. In your two cases, it is mylibraryactually imported in both your "unconditional" and "conditional" cases. If you want to import the library conditionally, use the requireruntime construct.

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

use . , require mylibrary->import , use. import , , , - import , .

, mylibrary foo. :

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

:

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

, , mylibrary . , , .

+7

, use ( → ) if pragma: http://perldoc.perl.org/if.html

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

, , , if , , , .

0

All Articles