我有两个文本文件,包含品种的柱状数据position
- value
,排序依据position
.
以下是第一个文件(文件A
)的示例:
100 1
101 1
102 0
103 2
104 1
...
Run Code Online (Sandbox Code Playgroud)
这是第二个文件(B
)的示例:
20 0
21 0
...
100 2
101 1
192 3
193 1
...
Run Code Online (Sandbox Code Playgroud)
而不是将两个文件中的一个读入哈希表,这是由于内存限制而禁止的,我想要做的是以逐步的方式同时遍历两个文件.
这意味着我想通过其中任何一行A
或B
比较position
值进行流式传输.
如果两个位置相等,则我对与该位置相关的值进行计算.
否则,如果位置不相等,我会移动文件A
或文件行,B
直到位置相等(当我再次执行计算时)或我达到两个文件的EOF.
有没有办法在Perl中执行此操作?
看起来像是一个可能偶然发现的问题,例如具有键和值的数据库表数据.这是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);
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
如果文件已排序,则根据位置较低的文件逐步浏览它们。
伪代码:
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
Run Code Online (Sandbox Code Playgroud)
您还可以使用join(1)来隔离具有共同位置的行,并在闲暇时对其进行处理。
归档时间: |
|
查看次数: |
9584 次 |
最近记录: |