我什至从 perldoc
阅读了解释和 StackOverflow
.但是有一点困惑。
use
通常在编译时加载模块,而 require
在运行时执行 use
仅调用内置的导入函数,而 require
需要单独调用导入模块,如BEGIN {
require ModuleName;
ModuleName->import;
}
require
如果我们想偶尔加载更大的模块,则使用它。 use
在较早的状态抛出异常,而 require
当我遇到问题时会这样做use
我们可以选择性地加载程序,而不是全部,但很少像use Module qw(foo bar) # it will load foo and bar only
require
有可能吗?还?请注意
use
之间还有其他区别吗?和 require
?很多关于谷歌的讨论,但我只理解上面提到的这些点。
请帮助我其他观点。
最佳答案
这有点像 my
之间的区别。 , our
, 和 local
.区别很重要,但您应该使用 my
99% 的时间。
Perl 是一种相当古老而粗鲁的语言。多年来,它已经从组合的 awk/shell/kitchen sink 语言发展成为一种更强大的类型化和更强大的语言。
回到 Perl 3.x 中,在模块和包的概念固化之前的几天,没有模块有自己的函数和变量命名空间的概念。一切都随处可见。没有什么可导入的。 use
关键字不存在。你总是用require
.
到 Perl 5 出来的时候,模块已经有了自己的变量和子例程名称的存储。因此,我可以使用 $total
在我的程序和我的Foo::Bar
模块也可以使用 $total
因为我的$total
真的是$main::total
和他们的$total
真的是$Foo::Bar::total
.
导出是一种使模块中的变量和子例程可用于主程序的方法。这样,你可以说 copy( $file, $tofile);
而不是 File::Copy::copy( $file, $tofile );
.use
关键字只是为您自动化的东西。另外,use
在程序执行之前的编译时运行。这允许模块使用 prototyping , 所以你可以说 foo( @array )
而不是 foo( \@array )
或 munge $file;
而不是 munge( $file );
正如 use 中所说perldoc 的页面:
It [use] is exactly equivalent to:
BEGIN { require Module; Module->import( LIST ); }
基本上,您应该使用
use
超过 require
99% 的时间。我只能想到一个需要使用
require
的场合超过 use
, 但这只是为了模仿 use
.有时模块是可选的。如果 Foo::Bar
可用,我可以使用它,但如果它不可用,我不会。如果我能检查一下 Foo::Bar
就好了可用。让我们试试这个:
eval { use Foo::Bar; };
my $foo_bar_is_available = 1 unless ($@);
如果
Foo::Bar
不可用,我明白了:Can't locate Foo/Bar.pm in @INC (@INC contains:....)
那是因为
use
在我可以运行 eval 之前发生。但是,我知道如何模拟 use
与 require
:BEGIN {
eval { require Foo::Bar; Foo::Bar->import( qw(foo bar barfu) ); };
our foo_bar_module_available = 1 unless ($@);
}
这确实有效。我现在可以在我的代码中检查这一点:
our $foo_bar_module_available;
if ( $foo_bar_module_available ) {
fubar( $var, $var2 ); #I can use it
}
else {
... #Do something else
}
关于perl - use 和 require 的区别(我列出了区别,需要知道还有什么),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18231350/