I need to extract multiple substrings at fixed positions from a line and the same time replace whitespaces at another position.
For example, I have a string ‘01234567890 ‘. I want to extract characters at positions 1,2,6,7,8 and the same time if position 12, 13 are whitespaces, I want to replace them with 0101. It is all position based.
What is the best way to achieve this using perl ?
I can use substr and string comparison and then concatenate them together, but the code looked rather chuncky….
I would probably split (or: explode) the string into an array of single chars:
Now we can do array slices: extracting multiple arguments at once.
We can then turn the
@charsback into a string likeIf you want to remove certain chars instead of extracting them, you would have to use
slices inside a loop, an ugly undertaking.Complete sub with nice interface to do this kind of thing
Output: