【问题标题】:perl read multiple fileperl 读取多个文件
【发布时间】:2011-02-23 16:09:07
【问题描述】:

在 Perl 中,

如何一次读取多个文件,

在月底生成报告,

每天将创建一个日志文件,

我想阅读整个月的文件,

我的文件类似于 t.log.mmddyyy

【问题讨论】:

  • 首先:它是“Perl”。它不是首字母缩略词。其次,您尝试了什么,您拥有什么样的数据?请阅读有关如何提问的常见问题解答。

标签: perl


【解决方案1】:

glob 函数将允许您检索与特定模式匹配的文件名列表。如果您将该列表加载到@ARGV,那么您可以处理所有文件——甚至可以使用单个循环按顺序处理:

use strict;
use warnings;
use Getopt::Long;

sub usage ($) { 
    my $msg = shift;
    die <<"END_MSG";
*** $msg
Usage: $0 --month=nn --year=nn PATH

END_MSG
}

GetOptions( 'month=i' => \my $month, 'year=i'  => \my $year );

usage "Month not specified!" unless $month;
usage "Year not specified!"  unless $year;
usage "Invalid month specified: $month" unless $month > 0 and $month < 13;
usage "Invalid year specified: $year"   unless $year  > 0;

my $directory_path = shift;
die "'$directory_path' does not exist!" unless -d $directory_path;

@ARGV = sort glob( sprintf( "$directory_path/t.log.%02d??%02d", $month, $year ));
while ( <> ) { # process all files 
    ...
}

【讨论】:

    【解决方案2】:

    你可以做一个

    • readdir 获取目录中的文件列表
    • 解析每个文件名以确保它与您的格式匹配
    • 打开并读取每个文件

    【讨论】:

    • 但是目录包含整年,但我想读取每个月的文件,就像月底一样,我会发送报告,所以我想一次读取所有日志文件
    猜你喜欢
    • 2015-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 2013-11-14
    • 2017-08-05
    • 2013-07-11
    相关资源
    最近更新 更多