CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Regular Expressions:
I Need to replace names from 1 file everytime they occur in another file

 



jtra00
Novice

Jan 24, 2012, 8:32 AM

Post #1 of 3 (4981 views)
I Need to replace names from 1 file everytime they occur in another file Can't Post

I have 2 files:

file A
1. rabbit Number one like cookies
2. rat and companies created life
3. apple sauce is good
4. ice is water

File B

Rev_1 like carrot
rev_2 is a scientist best friend
Rev_3 saves Newton
Rev_4 is good for skating

How do I replace 1, 2, 3, 4, by rabbit, rat,apple, and ice in file B.
Thanks


rovf
Veteran

Jan 24, 2012, 9:23 AM

Post #2 of 3 (4976 views)
Re: [jtra00] I Need to replace names from 1 file everytime they occur in another file [In reply to] Can't Post

Replacement itself is easiest by substitution via regular expression. For example, if $s equals 'abc_3 X Y Z', the statement


Code
$s =~ /3/dogfood/;


changes $s into 'abc_dogfood X Y Z'.

To extract the values you need, from file A, you read it line by line, and use the split function.

The canonical way to store the association between the numbers (2) and keywords (rat) would be to use a hash. Since in your case, the numbers are continuous integers, you could also use an array, depending on what you feel more comfortable with.


jtra00
Novice

Jan 24, 2012, 9:29 AM

Post #3 of 3 (4974 views)
Re: [rovf] I Need to replace names from 1 file everytime they occur in another file [In reply to] Can't Post

Thank you very much. I have used Perl heavily years (7) ago and stopped. And I am back at it, now I have to relearn it again. I will try what you have suggested. Thanks
John

In Reply To

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives