I’m new with perl. saw many samples but had problems composing a solution
I have a list of strings which each string should be replaced in a different string a->a2, b->b34, etc. list of replacement is in some csv file. need to perform this replacement recursively on all files in directory.
might be any other language just thought perl would be the quickest
I’m new with perl. saw many samples but had problems composing a solution I
Share
Your problem can be split into three steps:
So lets do a countdown and see how we can do that 🙂
3. Search and replace
We will define a sub
searchAndReplace. It takes a file name as argument and accesses an outside hash. We will call this hash%replacements. Each key is a string we want to replace, and the value is the replacement. This “imposes” the restriction that there can only be one replacement per search string, but that should seem natural. I will further assume that each file is reasonably small (i.e. fits into RAM).This code is pretty straightforward, I escape the
$stringinside the regex so that the contents aren’t treated as a pattern. This implementation has the side effect of possibly replacing part of the$contentstring where something already was replaced, but one could work around that if this is absolutely neccessary.2. Traversing the file tree
We will define a sub called
anakinFileWalker. It takes a filename or a name of an directory and thesearchAndReplacesub as arguments. If the filename argument is a plain file, it does thesearchAndReplace, if it is a directory, it opens the directory and calls itself on each entry.Of course, this sub blows up if you have looping symlinks.
1. Setting up the
%replacementsThere is a nice module
Text::CSVwhich will help you with all your needs. Just make sure that the%replacementsmeet the definition above, but that isn’t hard.Starting it all
When the
%replacementsare ready, we just doand it should work. If not, this should have given you an idea about how to solve such a problem.