使用一个循环perl读取多个文件 [英] read multiple files using one loop perl
问题描述
我有2个文件,每个文件有50行.
i have 2 files each having 50 lines..
FILE1 FILE2
FILE1 FILE2
现在,我需要在一个while或for循环中逐行读取两个文件行,并且应该将相应的行推送到2个输出数组.我已经尝试过这样的事情.但无法解决.友善的帮助
now, i need to read two file lines by line in a single while or for loop and i should push the corresponding line to the 2 output arrays. i have tried something like this. but its not working out. kindly help
#!/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的值.
Here array 2 is not getting build.. but i am getting array 1 value.
推荐答案
在循环条件下,您将整个文件读入它们的数组.然后将列表分配用作布尔值.这仅工作一次,因为在评估条件之后将读取文件.另外,循环中的读取行将返回undef.
In your loop condition, you read the whole files into their arrays. The list assignment is then used as a boolean value. This works only once, as the files will be read after the condition has been evaluated. Also, the readlines inside the loop will return undef.
这是应该起作用的代码:
Here is code that should work:
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 feature 'say'
,并且将open
的3-arg形式与词汇文件句柄一起使用:
Of course, I am assuming that you did use strict; use warnings;
and use feature 'say'
, and used the 3-arg form of open
with lexical filehandles:
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: $!";
我还敦促您使用描述性的变量名而不是单个字母,并在尽可能深的范围内声明变量-在开始时声明vars几乎与使用错误的,错误的全局变量相同.
I also urge you to use descriptive variable names instead of single letters, and to declare your variables in the innermost possible scope — declaring vars at the beginning is almost the same as using bad, bad globals.
这篇关于使用一个循环perl读取多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!