3 Replies - 9339 Views - Last Post: 08 February 2013 - 02:06 AM

perl replace function

quick question, since perl is big about lists on both sides of the equation, I'm wondering if there's a replace function that will replace using a list.

Say, you have a variable pulled from a spreadsheet, and you need to account for certain abnormalities, such as ', ' or ' ' (doublespace), or other combinations.

In VB, you can do this, but requires nested replace functions, which is really ugly and hard to manage. Makes the code look like this 'replace(replace(<string>,<search>,<replace>),<search>,<replace>)...' and so on until you cover all you need to cover.

This is where perl's list operations would come in handy, and just use a list or a hash (hash would be better choice). Does this exist or should somebody make it happen?

Replies To: perl replace function

Re: perl replace function

Posted 03 February 2013 - 06:05 AM

Your VB example isn't really a list operation, it's simply passing the output of one function call as input to another function call without using an intermediate variable to store the result in between. In other words,

which would have the exact same end result, but it has the disadvantage of having to manually update the value of $pattern whenever you add another entry to %replacement. That approach would also get pretty cumbersome if you had a large number of replacement targets, so I prefer the solution with join for being more flexible and maintainable.