加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 23:24:34 所属栏目:大数据 来源:网络整理
导读:在perl中,有时需要在use语句中指定函数名称. 例如: use Data::DPath ('dpath'); 会工作但是 use Data::DPath; 惯于. 其他模块不需要指定的函数名称,例如: use WWW::Mechanize; 为什么? 解决方法 每个模块默认选择它导出的功能.有些人默认情况下选择不输出
在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();关闭导出.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读