我有每一个具有50行2个文件..
FILE1 FILE2
现在,我需要在一个单一的,同时或for循环读取由线上的两个文件中的行和我应该推相应的线到2个输出阵列。 我曾尝试这样的事情。 但它不工作了。 好心帮
#!/usr/bin/perl
my @B =();
my @C =();
my @D =();
my $lines = 0;
my $i = 0;
my $sizeL = 0;
my $sizeR = 0;
my $gf = 0;
$inputFile = $ARGV[0];
$outputFile = $ARGV[1];
open(IN1FILE,"<$inputFile") or die "cant open output file ";
open(IN2FILE,"<$outputFile") or die "cant open output file";
while((@B=<IN1FILE>)&&(@C= <IN2FILE>))
{
my $line1 = <IN1FILE>;
my $line2 = <IN2FILE>;
print $line2;
}
这里阵列2没有得到建..但我得到阵列1的值。
在你的循环条件,你看整个文件到他们的阵列。 然后将列表分配作为一个布尔值。 这只有一次,视病情进行了评估后的文件将被读取。 另外,内循环readlines方法将返回undef。
下面是代码应工作:
my (@lines_1, @lines_2);
# read until one file hits EOF
while (!eof $INFILE_1 and !eof $INFILE_2) {
my $line1 = <$INFILE_1>;
my $line2 = <$INFILE_2>;
say "from the 1st file: $line1";
say "from the 2nd file: $line2";
push @lines_1, $line1;
push @lines_2, $line2;
}
你也可以这样做:
my (@lines_1, @lines_2);
# read while both files return strings
while (defined(my $line1 = <$INFILE_1>) and defined(my $line2 = <$INFILE_2>)) {
say "from the 1st file: $line1";
say "from the 2nd file: $line2";
push @lines_1, $line1;
push @lines_2, $line2;
}
要么:
# read once into arrays
my @lines_1 = <$INFILE_1>;
my @lines_2 = <$INFILE_2>;
my $min_size = $#lines_1 < $#lines_2 ? $#lines_1 : $#lines_2; # $#foo is last index of @foo
# then interate over data
for my $i ( 0 .. $min_size) {
my ($line1, $line2) = ($lines_1[$i], $lines_2[$i]);
say "from the 1st file: $line1";
say "from the 2nd file: $line2";
}
当然,我假设你没有use strict; use warnings;
use strict; use warnings;
和use feature 'say'
,并使用的3-arg格式open
与词法文件句柄:
my ($file_1, $file_2) = @ARGV;
open my $INFILE_1, '<', $file_1 or die "Can't open $file_1: $!"; # also, provide the actual error!
open my $INFILE_2, '<', $file_2 or die "Can't open $file_2: $!";
我也劝你使用描述性的变量名称,而不是单个字母,并在最里面的可能范围,声明变量 - 在一开始宣布瓦尔几乎一样使用坏,坏的全局。