Perl:合并多个文件(纯Perl)

use strict;
use warnings;
use IO::File;

my $dir    = “D:\\temp”;
my $suffix = “.log”;
my $target = “D:\\out.log”;
my @files  = ();

# 选择需要合并的文件,如在D:\temp下的*.log文件

opendir( my $dir_fh, $dir ) or die “Failed to open directory $dir: $!\n”;
while ( my $file = readdir($dir_fh) ) {
if ( $file =~ m/$suffix$/ ) {
push( @files, $file );
}
}
closedir($dir_fh);

# 合并所有被选中的文件
my $target_fh = new IO::File ” > $target ”
or print STDERR “Failed to create target file $target: $!\n”;
foreach (@files) {
my $file = $_;
my $fh   = new IO::File ” < $file ”
or print STDERR “Failed to open file $file: $!\n”;
print $target_fh (<$fh>);
undef $fh;
}
undef $target_fh;

Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s