本文介绍了`use` 包范围:如何使其跨文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scriptA.pl中,有use DBI

scriptB.pl中,有require "scriptA.pl"

但是我们仍然不能在scriptB.pl

除了在 scriptB.pl 中重复 use DBI 之外,还有什么方法可以解决这个问题?

Any way to handle this except repeating use DBI in scriptB.pl?

推荐答案

use 是一个文档化的特性:

The scoped nature of use is a documented feature:

从命名模块将一些语义导入当前包,通常是通过将某些子例程或变量名称别名到您的包中.

您可以通过回到石器时代来做您想做的事,如下例所示,但请不要这样做.

You could do what you want by going back to the stone age as in the following example, but please don't.

使用 MyModule 作为 DBI 的替代:

Using MyModule as a stand-in for DBI:

package MyModule;

use Exporter 'import';
our @EXPORT = qw/ foo /;
sub foo { print "$_[0]!\n" }

1;

然后从 scriptA.pl

foo "from scriptA";

和来自 scriptB.pl

foo "from scriptB";

全部从一个主程序开始

#! /usr/bin/perl

use warnings;
use strict;

use MyModule;

do "scriptA.pl" or die;
do "scriptB.pl" or die;

print "done.\n";

给出以下输出:

from scriptA!
from scriptB!
done.

您也可以在讨厌的 eval 游戏中禁用范围安全功能,但也请不要这样做.

You also could disable the scoping safety-feature with nasty eval games, but please don't do that either.

如果您的设计需要改进——也许 scriptAscriptB 属于同一个包——那将是更好的时间投资.否则,硬着头皮花费九次击键.

If your design needs improvement—maybe scriptA and scriptB belong in the same package—that would be a far better investment of your time. Otherwise, bite the bullet and expend nine keystrokes.

请注意,在运行时通过 dorequire 执行 Perl 库是一种严重过时的方法.perlmod 文档描述了现代方法.

Please note that executing Perl libraries at runtime via do or require are a seriously dated approaches. The perlmod documentation describes the modern approach.

这篇关于`use` 包范围:如何使其跨文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 23:44