我有两个文本文件,其中包含position-value类型的列数据,按position排序。
以下是第一个文件(文件A)的示例:
100 1
101 1
102 0
103 2
104 1
...下面是第二个文件(B)的示例:
20 0
21 0
...
100 2
101 1
192 3
193 1
...我想做的不是将两个文件中的一个读取到哈希表中,而是以一种分步的方式同时遍历两个文件。
这意味着我希望通过A或B行进行流式处理,并比较position值。
如果两个位置相等,则对与该位置关联的值执行计算。
否则,如果位置不相等,我将遍历文件A或文件B的行,直到位置相等(当我再次执行计算时)或到达这两个文件的EOF为止。
有没有办法在Perl中做到这一点?
发布于 2010-03-23 19:13:04
看起来像是一个人们可能会偶然遇到的问题,例如带有键和值的数据库表数据。下面是rjp提供的伪代码的一个实现。
#!/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);希望这能有所帮助!
发布于 2010-03-23 18:17:59
如果对文件进行了排序,则根据哪个文件的位置较低来逐步执行这些文件。
伪码:
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)来隔离具有公共位置的行,并在空闲时对其进行处理。
发布于 2010-03-23 18:10:08
对于遍历文件,您可以使用核心Tie::File模块。它将常规文本文件表示为数组。
https://stackoverflow.com/questions/2498937
复制相似问题