Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

using a hash to replace values in a file 1

Status
Not open for further replies.

ailse

Programmer
Jan 20, 2004
79
GB
Hi,

I am trying to use a hash as a lookup to replace 'placeholders' in a file. I have some raw data that I have read into a hash which looks like this:

Code:
id1 val1
id2 val2
id3 val3

so the keys of the hash are the id's. I have another file which looks like this:

Code:
enzyme: id1
interacts with: id2 id3

enzyme: id4
interacts with: id6 id7

and so on. What i'd like to do is scan the file, using the hash to replace the id's with the actual values they are associated with, so that it looks like this:

Code:
enzyme: val1
interacts with: val2 val3

enzyme: val4
interacts with: val6 val7

hope that makes sense... i have tried a pattern matching approach to test each line to see if it contains a hash key, but can't seem to get it right. if anyone has more of a clue than me, that would be fantastic!

many thanks.
 
You can use a regex substitution to look up the value of $1 in your hash (see the e modifier on the substitution). This would be OK for simple files where ther is no chance of you inadvertently matching and replacing something you shouldn't.

For anything more complex, check out Template::Toolkit, which can process your 'template' file and substitute anything you want, conditionally, with loops, includes, and a whole load of other bells and whistles besides.

For a simple example like this, all you'd need to do is pass it the hash and the template, and tell it where to put the output...

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
Thanks Steve, I'd never heard of this module before, I'll give it a go :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top