在perl中一次处理多个文件? [英] Working through multiple files one at a time in perl?

查看:231
本文介绍了在perl中一次处理多个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个perl脚本,可以打开一个txt文件,对其进行解析,以便将适当的文本输出到一个csv文件中.我现在为一个文件工作得很好,但是我有很多相似的文件可以以完全相同的方式进行处理.我希望能够自动执行此操作,因此代码将通过file1.txt进行工作并解析要输出的文本.然后通过file2.txt并将此输出附加到相同的output.csv.我在下面包含了我的代码的relevan位,仅排除了在while循环内进行实际解析的代码,因为我不需要更改此代码.输入文件的名称是一致的,例如file1.txt,file2.txt,file3.txt等,并且都位于同一目录中

I have a perl script that opens a txt file, parses it so that the appropriate text is output to a csv file. I have working great now for one file, but I have loads of similar files to work through in the exact same way. I want to be able to just do this automatically so the code will work through file1.txt and parse the text I want to output.csv, then work through file2.txt and append this output to the same output.csv. I have included the relevan bits of my code below, excluding only the code that does the actual parsing within the while loop since I don't need to alter this. The input files are consistently named, e.g. file1.txt, file2.txt, file3.txt etc. and all reside in the same directory

my $mode = "none";
open(my $infile,"<","file1.txt") or die $!;
open (my $outfile,">>","output.csv") or die $!;
while (<$infile>)
{
    chomp; 
    if ($_ =~ /^Section 1/) {
        $mode = "sec1";
    }
    if ($_ =~ /^Section 2/) {
        $mode = "sec2";
    }

    if ($mode =~ "sec1") {
      $_=~ tr/,//d;

      if ($_ =~ /.\%$/){
        print $outfile $_;
        print $outfile "\n";
      }
      else{
        print $outfile $_;  
      }

    }    
}

close $infile;
close $outfile;

输出文件应该类似于此文件(显然不是该文本,我只是强调它必须附加输出,我认为我已经使用>>而不是>覆盖了它)

The output file should resemble this (not this text obviously, I'm just highlighting that it the output must be appended, which I think I have covered by using >> as opposed to >)

this is from file 1
this is from file 2
this is from file 3

推荐答案

您只需要将其包装在这样的循环中即可:

You just need to wrap this in a loop like so:

for my $file ( @list_files ) {
    open $in_fh, "<", $file;
    while (my $line = <$in_fh>) {
    # and the rest of your stuff goes here

这篇关于在perl中一次处理多个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆