0

我正在执行以下步骤:

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

任何帮助将不胜感激。

4

2 回答 2

6

require函数试图变得聪明并仅在尚未加载代码时才加载代码。为什么这么棒?(1.) 我们没有条件包含的 C 预处理器地狱,并且 (2.) 我们节省了时间。

要执行另一个 perl 脚本,我们有多种可能。您可能想要的是do脚本。do FILENAME语法就像 eval,除了你的范围对 ne 文件不可见do

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

您可以制作test3.pl一个模块,例如 with 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不存在。

这是否有效也取决于您正在调用的脚本。

于 2012-09-22T04:32:10.550 回答
0

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

于 2012-09-22T04:15:00.457 回答