为什么必须在use语句中指定函数名?

前端之家收集整理的这篇文章主要介绍了为什么必须在use语句中指定函数名?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在perl中,有时需要在use语句中指定函数名称.

例如:

use Data::DPath ('dpath');

会工作但是

use Data::DPath;

惯于.

其他模块不需要指定的函数名称,例如:

use WWW::Mechanize;

为什么?

解决方法

每个模块默认选择它导出的功能.有些人默认情况下选择不输出任何功能,你必须要求它们.这样做有几个很好的理由,其中一个很糟糕.

如果你是像WWW::Mechanize这样的类,那么你不需要导出任何函数.一切都是类或对象方法.我的$mech = WWW :: Mechanize-> new.

如果你是像strict那样的pragma,那么就没有函数也没有方法,它只是通过加载来完成它的工作.

默认情况下,某些模块导出太多函数.一个例子是Test::Deep,它出口……

all any array array_each arrayelementsonly arraylength arraylengthonly bag blessed bool cmp_bag cmp_deeply cmp_methods cmp_set code eq_deeply hash
hash_each hashkeys hashkeysonly ignore Isa isa listmethods methods noclass
none noneof num obj_isa re reftype regexpmatches regexponly regexpref
regexprefonly scalarrefonly scalref set shallow str subbagof subhashof
subsetof superbagof superhashof supersetof useclass

当另一个模块尝试导出相同的函数,或者如果您编写具有相同名称函数时,问题就出现了.然后他们发生冲突,你会收到神秘的警告.

$cat ~/tmp/test.plx
use Test::Deep;
use List::Util qw(all);

$perl -w ~/tmp/test.plx
Subroutine main::all redefined at /Users/schwern/perl5/perlbrew/perls/perl-5.20.2/lib/5.20.2/Exporter.pm line 66.
 at /Users/schwern/tmp/test.plx line 2.
Prototype mismatch: sub main::all: none vs (&@) at /Users/schwern/perl5/perlbrew/perls/perl-5.20.2/lib/5.20.2/Exporter.pm line 66.
 at /Users/schwern/tmp/test.plx line 2.

因此,不鼓励输出大量功能.例如,the Exporter documentation advises ……

Do not export method names!

Do not export anything else by default without a good reason!

Exports pollute the namespace of the module user. If you must export try to use @EXPORT_OK in preference to @EXPORT and avoid short or common symbol names to reduce the risk of name clashes.

不幸的是,有些模块太过分了. Data::DPath就是一个很好的例子.它有一个非常清晰的主函数dpath(),默认情况下它应该导出.否则它基本上没用.

您始终可以使用Some :: Module();关闭导出.

猜你在找的Perl相关文章