【问题标题】:help merging perl code routines together for file processing帮助将 perl 代码例程合并在一起以进行文件处理
【发布时间】:2011-02-19 17:01:39
【问题描述】:

我需要一些 perl 帮助来将这些 (2) 进程/代码放在一起工作。我能够让它们单独工作以进行测试,但我需要帮助将它们组合在一起,尤其是在使用循环结构时。我不确定我是否应该使用 foreach..反正代码如下。

此外,当我正在学习这门语言时,任何最佳实践都会很棒。感谢您的帮助。

这是我正在寻找的流程:

  • 读取目录
  • 查找特定文件
  • 使用文件名剥离一些关键信息,创建一个新处理的文件
  • 处理输入文件
  • 为每个读取的输入文件创建新处理的文件(如果我读入 10 个,我会创建 10 个新文件)

第 1 部分:

my $target_dir = "/backups/test/";
opendir my $dh, $target_dir or die "can't opendir $target_dir: $!";
while (defined(my $file = readdir($dh))) {
    next if ($file =~ /^\.+$/);
    #Get filename attributes
    if ($file =~ /^foo(\d{3})\.name\.(\w{3})-foo_p(\d{1,4})\.\d+.csv$/) {
      print "$1\n";
      print "$2\n";
      print "$3\n";
    }
    print "$file\n";
}

第 2 部分:

use strict;
use Digest::MD5 qw(md5_hex);
#Create new file
open (NEWFILE, ">/backups/processed/foo$1.name.$2-foo_p$3.out") || die "cannot create file";
my $data = '';
my $line1 = <>;
chomp $line1;
my @heading = split /,/, $line1;
my ($sep1, $sep2, $eorec) = ( "^A", "^E", "^D");
while (<>)
{
    my $digest = md5_hex($data);
    chomp;
    my (@values) = split /,/;
    my $extra = "__mykey__$sep1$digest$sep2" ;
    $extra .= "$heading[$_]$sep1$values[$_]$sep2" for (0..scalar(@values));
    $data .= "$extra$eorec"; 
    print NEWFILE "$data";
}
#print $data;
close (NEWFILE);

【问题讨论】:

    标签: perl foreach while-loop fileparsing


    【解决方案1】:

    您使用的是旧式 Perl 编程。我建议您使用函数和 CPAN 模块 (http://search.cpan.org)。 Perl 伪代码:

    use Modern::Perl;
    # use... 
    
    sub get_input_files {
      # return an array of files (@)
    }
    
    sub extract_file_info {
       # takes the file name and returs an array of values (filename attrs)
    }
    
    sub process_file {
       # reads the input file, takes the previous attribs and build the output file
    }
    
    
    my @ifiles = get_input_files;
    foreach my $ifile(@ifiles) {
       my @attrs = extract_file_info($ifile);
       process_file($ifile, @attrs);
    }
    

    希望对你有帮助

    【讨论】:

    • 是的,确实如此。此外,它比任何其他编程风格都更有效。
    • 好的,从长远来看,我可以看到,但如果可以的话,我想让它工作。谢谢。
    【解决方案2】:

    我已经将您的两个代码片段组合在一起(使第二个代码片段成为sub,第一个调用每个匹配文件),如果我正确理解了您对目标的描述,这应该可以满足您的需求。样式和语法的注释是内联的:

    #!/usr/bin/env perl
    
    # - Never forget these!
    use strict;
    use warnings;
    
    use Digest::MD5 qw(md5_hex);
    
    my $target_dir = "/backups/test/";
    opendir my $dh, $target_dir or die "can't opendir $target_dir: $!";
    while (defined(my $file = readdir($dh))) {
        # Parens on postfix "if" are optional; I prefer to omit them
        next if $file =~ /^\.+$/;
        if ($file =~ /^foo(\d{3})\.name\.(\w{3})-foo_p(\d{1,4})\.\d+.csv$/) {
            process_file($file, $1, $2, $3);
        }
        print "$file\n";
    }
    
    sub process_file {
        my ($orig_name, $foo_x, $name_x, $p_x) = @_;
    
        my $new_name = "/backups/processed/foo$foo_x.name.$name_x-foo_p$p_x.out";
    
        # - From your description of the task, it sounds like we actually want to
        #   read from the found file, not from <>, so opening it here to read
        # - Better to use lexical ("my") filehandle and three-arg form of open
        # - "or" has lower operator precedence than "||", so less chance of
        #   things being grouped in the wrong order (though either works here)
        # - Including $! in the error will tell why the file open failed
        open my $in_fh, '<', $orig_name or die "cannot read $orig_name: $!";
        open(my $out_fh, '>', $new_name) or die "cannot create $new_name: $!";
    
        my $data  = '';
        my $line1 = <$in_fh>;
        chomp $line1;
        my @heading = split /,/, $line1;
        my ($sep1, $sep2, $eorec) = ("^A", "^E", "^D");
        while (<$in_fh>) {
            chomp;
            my $digest   = md5_hex($data);
            my (@values) = split /,/;
            my $extra    = "__mykey__$sep1$digest$sep2";
            $extra .= "$heading[$_]$sep1$values[$_]$sep2"
              for (0 .. scalar(@values));
            # - Useless use of double quotes removed on next two lines
            $data .= $extra . $eorec;
            #print $out_fh $data;
        }
        # - Moved print to output file to here (where it will print the complete
        #   output all at once) rather than within the loop (where it will print
        #   all previous lines each time a new line is read in) to prevent
        #   duplicate output records.  This could also be achieved by printing
        #   $extra inside the loop.  Printing $data at the end will be slightly
        #   faster, but requires more memory; printing $extra within the loop and
        #   getting rid of $data entirely would require less memory, so that may
        #   be the better option if you find yourself needing to read huge input
        #   files.
        print $out_fh $data;
    
        # - $in_fh and $out_fh will be closed automatically when it goes out of
        #   scope at the end of the block/sub, so there's no real point to
        #   explicitly closing it unless you're going to check whether the close
        #   succeeded or failed (which can happen in odd cases usually involving
        #   full or failing disks when writing; I'm not aware of any way that
        #   closing a file open for reading can fail, so that's just being left
        #   implicit)
        close $out_fh or die "Failed to close file: $!";
    }
    

    免责声明:perl -c 报告此代码在语法上有效,但未经测试。

    【讨论】:

    • 谢谢!它现在运作良好。它对我来说是一个很好的例子。我不确定如何正确使用打开的文件并使用&lt;&gt;。
    • 我实际上在 outfile 上获得了一些 dup 记录。如果我在close $out_fh 行之后添加 $print $data,我可以看到它将打印正确数量的记录。让我知道我是否遗漏了什么。谢谢。
    • @jdamae:啊,是的。你说问题中的代码有效(就它而言),所以我没有仔细研究它。您应该只在循环结束时将$extra(最新行)打印到$out_fh,而不是$data(到目前为止从文件中读取的所有行)。我还将编辑我的答案以解决此问题。
    • @jdamae:好的,所以我改变了主意并以不同于我所说的方式解决了重复问题......但我还在代码中添加了一条注释,解释了我为什么选择这样做另一种方式以及每种方式的相对好处是什么。
    猜你喜欢
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多