【问题标题】:(Perl) Running the same code for multiple files(Perl) 为多个文件运行相同的代码
【发布时间】:2013-01-09 10:14:16
【问题描述】:

截至目前,我有 22 个文件和 22 个独立但相同(在任务中)的每个文件的脚本。基本上,这就是我所拥有的:

file_1.txt, file_2.txt,..., file_22.txt

对于每个文件,我都有一个脚本:

script_1.pl, script_2.pl,..., script_22.pl

输出

output_1.txt, output_2.txt,..., output_22.txt

分别。

我现在要做的是编写一个脚本,它将同时运行所有脚本(script_1.pl - script_22.pl),这样我就不必每次都单独运行它们更新我的文件。它们都分开的原因是因为我不知道如何循环文件名,并为每个文件名分配一个新的输出文件。我希望有人能帮我解决这个问题:一个脚本可以一次读取所有文件,为每个文件运行脚本(它是一个相同的脚本),然后为每个文件打印一个新的输出文件,如上所列。

编辑:我想我应该包括我现在拥有的东西。我确实有一些可行的方法,但它仍然依赖于我拥有 22 个单独的脚本这一事实。我一直在做的事情如下:

system("perl script_1.pl");

system("perl script_2.pl");

...

system("perl script_22.pl");

我希望能够将所有内容组合成一个紧凑的脚本。任何帮助将不胜感激!提前致谢!

【问题讨论】:

  • 如果脚本相同,为什么不将输入和输出文件名统一为arguements?不是script_1.pl,而是./script.pl file_1.txt output_1.txt

标签: perl


【解决方案1】:

您可以从@ARGV 获取程序参数列表,然后在for 循环中运行您的代码。

for my $input_file (@ARGV) {
    my $output_file = $input_file.".out";

    process_file($input_file, $output_file);
}

sub process_file {
    my($input_file, $output_file) = @_;

    ...do whatever you like with the input and output file...
}

然后你可以像这样运行你的程序:

myprogram file1 file2 file3

它会读取file1、file2和file3并产生file1.out、file2.out和file3.out。

这是一些非常基本的编程和一些非常基本的 Perl。您可能应该备份并阅读一些 Perl 入门书籍。我可以推荐一下最近刚刚发布的Curtis Poe's Beginning Perl。

【讨论】:

  • 也许应该指定process_file 应该包含主脚本的代码,而不是system("script.pl $input $output")。
  • 谢谢!是的,我实际上是因为一个研究项目才开始使用 Perl,所以我还有很多基础知识需要掌握。我一定会看看那本书!
【解决方案2】:

假设您可以访问Bash:

$ for f in file_*.txt; do script.pl "$f" > "${f/file_/output_}"; done

这将为每个输入文件 (file_n.txt) 创建一个输出文件 (output_n.txt)。如果你使用简单的名字(没有空格等),你可以去掉双引号

【讨论】:

    【解决方案3】:

    我已经有一段时间没有锻炼我的 perl 肌肉了。但是试试这个来消除你的问题。

    for(my $index= 1,$index<=22,$index++){
       my $inputfile = "file_$index.txt";
       my $outputfile = "output_$index.txt";
    
       system("perl OneScriptToRuleThemAll.pl $inputfile $outputfile");
    }
    

    OneScriptToRuleThemAll.pl 是我的 `script_1.pl .. script_22.pl 中的 1 个统一脚本的愚蠢版本。

    需要修改脚本以解析 @Argv 以获取输入文件和输出文件参数,而不是对它们进行硬编码。

    【讨论】:

      【解决方案4】:
      system "script_$_.pl" for (1..22);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多