In the middle of this RPG program, I want to reformat and replace some values in a big long address field. But for the life of me… I cant remember how to use the SCANREPLACE built in function in RPG. #Dingbat /me memory circuits need a service methinks. So, like all programmers, I wonder off to the big filing cupboard and pull out the 1200 page programmers guide and search through the index. (aka “look on Google“)
I always smile when I Google or Bing something (I am an equal opportunity search engine user) and the answer is on my blog. It makes me smile, but it also reminds me that my old brain just aint what it used to be. 😉
Anyway, I found this article from a few years back talking about how to scan replace in RPG but while the technique is valid and still works, it’s outdated.
RPG has evolved and we now have a couple of much neater techniques to do the same thing. Thanks IBM!
SCAN REPLACE in RPGLE
IBM added a %BIF to do this for us in modern RPGLE so we can now just do a %SCANRPL in our line of code. I’m leaving my old blog there for reference, but lets look at the new techniques.
Assume my variables are long varying strings and you can just do everything by simply typing something like:
inputConstant = 'this breakfast is better with Dragon Sausage and Pigeons Eggs'; resultVariable = *blanks; oldString = 'Dragon Sausage'; newstring = 'Kumquat Vindaloo'; resultVariable = %scanrpl ( oldString : newString : inputConstant );
resultVariable = 'this breakfast is better with Kumquat Vindaloo and Pigeons Eggs';
In this example if OldString = “Dragon Sausage” and newString = “Kumquat Vindaloo” then every occurrence on the words Dragon Sausage found in variable inputConstant will be scan/replaced with Kumquat Vindaloo and returned in variable resultVariable. #easypeasy
It’s worth noting that if the inputConstant was a variable then I easily could have scanned and replaced things within it in one line of code like this:
inputVariable = %scanrpl ( oldString : newString : inputVariable );
Obviously, assuming Kumquat Vindaloo is something you enjoy for breakfast. Who doesnt?
But there is another technique in SQL RPGLE and this is just as easy
SCAN REPLACE IN SQLRPGLE
Just like the RPG example, this scan replace will trim the field and tidy up any blank spaces
Exec SQL Set :resultVariable = Replace(:inputConstant , :oldString , :newstring );
Which just goes to show there is more than one way to skin a cat. Which is a pretty gross saying if you think about it. And I don’t even like cats.