首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Perl中同时遍历两个文件?

问如何在Perl中同时遍历两个文件?
EN

Stack Overflow用户
提问于 2010-03-23 18:05:53
回答 4查看 10.9K关注 0票数 8

我有两个文本文件,其中包含position-value类型的列数据,按position排序。

以下是第一个文件(文件A)的示例:

代码语言:javascript
复制
100   1
101   1
102   0
103   2
104   1
...

下面是第二个文件(B)的示例:

代码语言:javascript
复制
20    0
21    0
...
100   2
101   1
192   3
193   1
...

我想做的不是将两个文件中的一个读取到哈希表中,而是以一种分步的方式同时遍历两个文件。

这意味着我希望通过A或B行进行流式处理,并比较position值。

如果两个位置相等,则对与该位置关联的值执行计算。

否则,如果位置不相等,我将遍历文件A或文件B的行,直到位置相等(当我再次执行计算时)或到达这两个文件的EOF为止。

有没有办法在Perl中做到这一点?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-03-23 19:13:04

看起来像是一个人们可能会偶然遇到的问题,例如带有键和值的数据库表数据。下面是rjp提供的伪代码的一个实现。

代码语言:javascript
复制
#!/usr/bin/perl

use strict;
use warnings;

sub read_file_line {
  my $fh = shift;

  if ($fh and my $line = <$fh>) {
    chomp $line;
    return [ split(/\t/, $line) ];
  }
  return;
}

sub compute {
   # do something with the 2 values
}

open(my $f1, "file1");
open(my $f2, "file2");

my $pair1 = read_file_line($f1);
my $pair2 = read_file_line($f2);

while ($pair1 and $pair2) {
  if ($pair1->[0] < $pair2->[0]) {
    $pair1 = read_file_line($f1);
  } elsif ($pair2->[0] < $pair1->[0]) {
    $pair2 = read_file_line($f2);
  } else {
    compute($pair1->[1], $pair2->[1]);
    $pair1 = read_file_line($f1);
    $pair2 = read_file_line($f2);
  }
}

close($f1);
close($f2);

希望这能有所帮助!

票数 6
EN

Stack Overflow用户

发布于 2010-03-23 18:17:59

如果对文件进行了排序,则根据哪个文件的位置较低来逐步执行这些文件。

伪码:

代码语言:javascript
复制
read Apos, Aval from A # initial values
read Bpos, Bval from B 
until eof(A) or eof(B)
  if Apos == Bpos then
    compare()
    read Apos, Aval from A # advance both files to get a new position
    read Bpos, Bval from B
  fi
  if Apos < Bpos then read Apos, Aval from A
  if Bpos < Apos then read Bpos, Bval from B
end

您还可以使用join(1)来隔离具有公共位置的行,并在空闲时对其进行处理。

票数 5
EN

Stack Overflow用户

发布于 2010-03-23 18:10:08

对于遍历文件,您可以使用核心Tie::File模块。它将常规文本文件表示为数组。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2498937

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档