Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: merging content based on common columns of 2 files using grep

by citromatik (Curate)
on May 06, 2009 at 11:49 UTC ( #762235=note: print w/ replies, xml ) Need Help??


in reply to merging content based on common columns of 2 files using grep

First of all, you should use strict; and use warnings; if you want to learn Perl the easy way

There are some errors in your code, some of them:

  • file1.txt and file2.txt are literal strings, so you should put them in quotation marks
  • After read a file, you should chomp the line/s read
  • The syntax you are using for grep is not correct, you should be using grep BLOCK LIST

Here is a working version of your program:

use strict; use warnings; open(FH1,"file1.txt"); open(FH2,"file2.txt"); my @array=<FH2>; chomp @array; while(my $var=<FH1>){ chomp $var; my ($first,$second)=split(/\s+/,$var); my @grepped= grep {/\Q$second\E/} @array; print "$first\t$grepped[0]\n"; }

You should also consider using hashes to solve your problem

Another alternative, if the script is only going to join both files and output the result (and you are in a Unix/Linux system, as it seems to be the case) is to use bash's join tool:

$ join -1 2 -2 1 file1.txt file2.txt

citromatik


Comment on Re: merging content based on common columns of 2 files using grep
Select or Download Code
Re^2: merging content based on common columns of 2 files using grep
by heidi (Sexton) on May 06, 2009 at 15:04 UTC
    thank u :)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://762235]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (13)
As of 2014-07-22 14:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (115 votes), past polls