How can I walk through two files simultaneously in Perl?

Posted by Alex Reynolds on Stack Overflow See other posts from Stack Overflow or by Alex Reynolds
Published on 2010-03-23T10:05:52Z Indexed on 2010/03/24 0:13 UTC
Read the original article Hit count: 371

Filed under:
|
|

I have two text files that contain columnar data of the variety position-value, sorted by position.

Here is an example of the first file (file A):

100   1
101   1
102   0
103   2
104   1
...

Here is an example of the second file (B):

20    0
21    0
...
100   2
101   1
192   3
193   1
...

Instead of reading one of the two files into a hash table, which is prohibitive due to memory constraints, what I would like to do is walk through two files simultaneously, in a stepwise fashion.

What this means is that I would like to stream through lines of either A or B and compare position values.

If the two positions are equal, then I perform a calculation on the values associated with that position.

Otherwise, if the positions are not equal, I move through lines of file A or file B until the positions are equal (when I again perform my calculation) or I reach EOF of both files.

Is there a way to do this in Perl?

© Stack Overflow or respective owner

Related posts about perl

Related posts about file-io