How can I walk through two files simultaneously in Perl?

前端 未结 4 456
滥情空心
滥情空心 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:24

    Here is a quick solution. If the data in both files is pretty much equivalent (e.g. same number of lines), you don't really need to store in hash tables. But I thought it would be helpful in case you the data is scrambled.

    Code:

    open(f1, ") and ($line2 = )){
         chomp($line1);
         chomp($line2);
         # split fields 1 and 2 into an array
         @LINE1 = split(/\t/, $line1);
         @LINE2 = split(/\t/, $line2);
         # store data into hashes
         $data1{$LINE1[0]} = $LINE1[1];
         $data2{$LINE2[0]} = $LINE2[1];
         # compare column 2
         if ($data1{$LINE2[0]} == $data2{$LINE1[0]}){
               # compute something
               $new_val = $data1{$LINE2[0]} + $data2{$LINE1[0]};
               print $LINE1[0] . "\t" . $new_val . "\n";
         } else {
               print $LINE1[0] . "\t" . $data1{$LINE1[0]} . "\n";
         }
    }
    

    I hope it helps and let me know if its useful.

提交回复
热议问题