How can I walk through two files simultaneously in Perl?

前端 未结 4 420
滥情空心
滥情空心 2020-12-31 18:36

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

Here is an example of the

4条回答
  •  有刺的猬
    2020-12-31 19:16

    Looks like a problem one would likely stumble upon, for example database table data with keys and values. Here's an implementation of the pseudocode provided by 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);
    

    Hope this helps!

提交回复
热议问题