這裏有一個更好的主意:
#!/usr/bin/perl
use warnings;
use strict;
use File::Slurp qw<append_file read_file>;
my @input_files = ('a'..'z');
foreach my $file_name (@input_files) {
my $contents = read_file("/home/${file_name}_all.txt");
append_file("/home/${file_name}${_}_all.txt", $contents) foreach 2..3;
}
我沒有看到你作爲對正在寫出的內容進行更改,因此您聽起來像只想將${letter}_all.txt
轉儲到${letter}${num}_all.txt
。
或者,如果你想知道怎麼做標準的Perl更理智的版本,我做了以下更改。
use warnings;
use strict;
use English qw<$OS_ERROR>;
my $_arry_counter = 1;
# no reason to write the whole alphabet
my @input_files_1 = 'a'..'z';
# I'm not sure what you thought you could do with your foreach loop expression.
foreach my $file_names (@input_files_1) {
# save! the path
my $path = "/home/${file_names}_all.txt";
# open *lexical* handles and die with *explicit* message and OS error.
open my $input,'<', $path or die "unable to open file '$path'! - $OS_ERROR";
# best way to do this to minimze IO is to write two files at once to two
# two different handles.
my @outs
= map {
# repeating practice with inputs
my $out_path = "/home/${file_names}$_\_all.txt";
open my $out, '>>', or die "unable to open file '$out_path'! - $OS_ERROR";
$out;
} 2..3;
while (my $line = <$input>) {
# in this foreach $_ is a handle, so we need to save the line in a var.
print $_ $line foreach @outs;
}
# close each output
close $_ foreach @outs;
# close current input
close $input;
}
我的,你放什麼意見的版本,會更喜歡這樣的:
use English qw<$RS>; # record separator -> $/
my $regex = qr{
(^ \@ .*)
# note that I turn on s for *select* sections
((?s) .*?)
(^ (windows|linux) .*)
((?s) .*?)
(^ (windows|linux) .*)
((?s) .*?)
}mx;
foreach my $file_name (@input_files) {
my $contents = read_file("/home/jbutler/final/${file_name}_all.txt");
local $RS = 'Data';
$contents =~ s/$regex/$1$2$3$4\n__Data__\n$1\n$5$6/m;
append_file("/home/jbutler/final/${file_name}${_}_all.txt", $contents) foreach 2..3;
}
但是我沒有測試過這一點。
你能解釋(或固定)a3_all.txt - >您的要求設置的a3_all.txt一部分?我懷疑你打算給出4的錯字,但我們需要知道。 (可以說是一個箭頭'>'也是如此。) – 2011-04-01 15:53:22
不要在文件句柄周圍加引號!更妙的是,使用詞法文件句柄和3-arg open(),這個錯誤首先不會發生。 – tadmc 2011-04-01 21:27:54