如何在另一个Perl文件中重复使用Perl文件

  • 本文关键字:Perl 文件 另一个 perl
  • 更新时间 :
  • 英文 :


我正在执行以下步骤:

  • 读取目录中的所有文本文件,并将其存储在名为@files的数组中
  • 对每个文本文件运行foreach循环。使用拆分操作提取文件名(剥离.txt)并创建该特定文件名的文件夹。将该文件重命名为Test.txt(以便作为另一个perl可执行文件的输入)通过添加行require"test.pl"为每个文件执行test.pl

它只适用于一个文件,但不再适用。这是我的代码:

opendir DIR, ".";
my @files = grep {/.txt/} readdir DIR;
foreach my $files (@files) {
@fn = split '.', $files;
mkdir "$fn[0]" 
or die "Unable to create $fn[0] directory <$!>n";
rename "$files", "Test.txt";
require "test3.pl";
rename "Test.txt", "$files";
system "move $files $fn[0]";
}

任何帮助都将不胜感激。

require函数尝试智能化,并且仅在尚未加载代码的情况下才加载代码。为什么这么棒?(1.)我们没有C的带有条件includes的预处理器地狱,(2.)我们节省了时间。

要执行另一个perl脚本,我们有多种可能性。您可能想要的是do编写脚本。do FILENAME语法与eval类似,只是您的作用域对done文件不可见。

您也可以通过system "./test3.pl"启动另一个解释器。

您可以将test3.pl作为一个模块,例如使用package test3;,并将内容打包到sub中。您可能会将当前文件名作为参数传递,而不是硬编码文件名。这不仅是更好的编码实践,而且允许您更容易地扩展应用程序,例如多线程。

以下是我如何实现这个片段:

use test3; # load the file once
foreach my $file (glob "*.txt") {   # use `glob` to get a list of matching filenames
(my $newdir) = $file =~ m/^ (.+) .txt $/x;  # what you probably wanted
mkdir $newdir 
or die "Unable to create $newdir directory <$!>n";
test3::the_sub($file); # do the action on $file, without renaming circus.
system "move $file $newdir"; # rather use File::Copy
}

有趣的边点:glob非常棒,就像在shell中一样工作。

除非有充分的理由,否则始终使用my作为变量。

我进一步假设文件text.en.txt不应该创建目录text,而是text.en,并且文件.txt不存在。

这是否有效还取决于您调用的脚本。

使用do而不是requirerequire只加载并运行该文件一次。

最新更新