Perl merging columns in two text files -
i beginner perl , want merge content of 2 text files. have read similar questions , answers on forum, still cannot resolve issues first file has original id , recoded id of each individual (in first , fourth columns) second file has recoded id , information on of individuals (in first , second columns). want create output file original, recoded , information of these individuals. perl script have created far, not working. if appreciated.
use warnings; use strict; use diagnostics; use vars qw( @fields1 $recoded $original $idf @fields2); %columns1; open (file1, "<file1.txt") || die "$!\n couldn't open file1.txt\n"; while ($_ = <file1>) { chomp; @fields1=split /\s+/, $_; $recoded = $fields1[0]; $original = $fields1[3]; %columns1 = ( $recoded => $original ); }; open (file2, "<file2.txt") || die "$!\n couldnt open file2.txt \n"; ($_ = <file2>) { chomp; @fields2=split /\s+/, $_; $idf= $fields2[0]; $f=$fields2[1]; %columns2 = ( $f => $idf ); }; close file1; close file2; open (file3, ">output.txt") ||die "output problem\n"; (keys %columns1) { if (exists ($columns2{$_}){ print file3 "$_ $columns1{$_}\n" }; } close file3;
one problem scoping. in first loop, have my
in front of $column1
makes local loop , not in scope when next loop. %columns1
(which outside of loop) not have values set (which suspect want set). assignment, seem easier have $columns1{$recorded} = $original;
assigns value key hash.
in second loop need declare %columns2
outside of loop , possibly use above assignment.
for third loop, in print need add $columns2{$_}
in front part of string printed original id printed before recorded id.
Comments
Post a Comment