【问题标题】:read multiple files using one loop perl使用一个循环 perl 读取多个文件
【发布时间】:2013-02-03 14:55:48
【问题描述】:

我有 2 个文件,每个文件有 50 行..

文件 1 文件2

现在,我需要在单个 while 或 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 的值。

【问题讨论】:

  • 您的$outputFile 是否已填充?从空白文件读取时,您期望什么?您要修改输入吗?
  • 为什么它必须是一个while循环?
  • 您是要读取整个第一个文件然后读取第二个文件,还是重复读取第一个文件的一行然后第二个文件的一行?

标签: arrays perl loops


【解决方案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 feature 'say',并使用了带有词法文件句柄的 open 的 3-arg 形式:

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 几乎与使用糟糕的、糟糕的全局变量相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 2018-10-08
    • 2014-01-28
    • 2010-11-05
    • 1970-01-01
    相关资源
    最近更新 更多