gpt4 book ai didi

perl - 评估子程序时是否遵循 perl 模块的使用顺序?

转载 作者:行者123 更新时间:2023-12-04 22:54:20 26 4
gpt4 key购买 nike

我有一个 perl 模块,它有一个经常使用的子例程。对于一组特定的脚本,我需要覆盖这个子例程,所以我创建了另一个具有新实现的模块。有谁知道是否始终遵循 perl 模块的调用顺序?

前任。:
one.pm :

 sub temp{   print “hi”; }
two.pm :
sub temp{   print “hello”; }
sample.pl :
use one; use two;

temp();

我已经对此进行了测试,它按预期打印了“hello”。但我想确保情况始终如此。导入模块的评估是否一直井井有条?

最佳答案

你不应该这样写模块!您将遇到问题,包括您要询问的问题。使用 use 加载的任何文件应该有对应的package .他们必须以真正的值(value)结束。 (您的代码无法编译,因为您没有这样做。)

在我开始之前,让我提一下您应该始终使用 use strict; use warnings; .另请注意,小写模块名称传统上用于 pragma,即改变 Perl 本身行为方式的模块。将小写的模块名称用于其他目的是一种不好的做法。

回到正题。至少,您需要以下内容:
One.pm :

package One;
use strict;
use warnings;
sub temp { ... }
1;
Two.pm :
package Two;
use strict;
use warnings;
sub temp { ... }
1;

脚本现在看起来像这样:
use strict;
use warnings;
use One qw( );
use Two qw( );
One::temp();
Two::temp();

现在您看到您的问题没有实际意义;没有关于调用哪个 sub 的问题。

但是,如果您不想在所有调用前加上 One:: 怎么办?或 Two:: ?我们能做到这一点!
One.pm :
package One;
use strict;
use warnings;
use Exporter qw( import );
our @EXPORT_OK = qw( temp );
sub temp { ... }
1;
Two.pm :
package Two;
use strict;
use warnings;
use Exporter qw( import );
our @EXPORT_OK = qw( temp );
sub temp { ... }
1;

脚本现在看起来像这样:
use strict;
use warnings;
use One qw( );
use Two qw( temp );
One::temp();
Two::temp();
temp(); # Calls Two::temp() because we imported temp from Two.

如果您以某种方式执行了以下操作或等效操作,则最后一个将胜出。
use One qw( temp );
use Two qw( temp );

这就是为什么最好总是列出你导入的潜艇。不要使用
use Foo;         # Import default exports

相反,使用
use Foo qw( );   # Only import the listed exports. (None, in this case.)

如果不出意外,它还可以在维护模块时更容易找到 subs 及其文档。

关于perl - 评估子程序时是否遵循 perl 模块的使用顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59204393/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com