|TechTip: New in 7.1: The %SCANRPL Built-in Function|
|Tips & Techniques - RPG|
|Written by Steve Pitcher|
|Friday, 17 June 2011 00:00|
Replacing values has gotten a whole lot easier!
The new RPG IV built-in function %SCANRPL gives you the ability to scan a string for a value and then replace all occurrences with another value. The first parameter is the string you want to search for within another string. The second parameter is the string you want to replace it with. The third parameter is the string you want to scan. Simple.
This is pretty handy when we compare the way things used to be in the example below. You've got to find start positions, get lengths of strings, and set up loops to check for multiple instances of the same string. Also, a number of functions are called here—like %len, %scan, and %replace. It's all a bit messy and hard to read...and the first code example below is in free-format! I'm wondering what the equivalent code looks like in fixed-format RPG III...probably about as pretty as a well-lit exhibit of National Hockey League dental X-rays..
D search1 C 'iSeries.'
D search2 C 'OS/400'
D rep1 C 'Power Systems!'
D rep2 C 'IBM i'
D pos s 10i 0
string = 'I love OS/400 on iSeries.';
pos = %scan(search1: string);
dow pos > 0;
string = %replace(rep1: string: pos: %len(search1));
if (pos+%len(rep1) > %len(string));
pos = 0;
pos = %scan(search1: string: pos+%len(rep1));
pos = %scan(search2: string);
dow pos > 0;
string = %replace(rep2: string: pos: %len(search2));
if (pos+%len(rep2) > %len(string));
pos = 0;
pos = %scan(search2: string: pos+%len(rep2));
//string = 'I love IBM i on Power Systems!'
Instead, by using the %SCANRPL built-in function, we're able to cut out every loop, variable, if, and else and produce a very simple few lines of code to achieve the same results.
string1 = 'I love OS/400 on iSeries.';
string2 = %ScanRpl('iseries.' : 'Power Systems!' : string1);
string3 = %ScanRpl('OS/400' : 'IBM i' : string2);
// string3 = 'I love IBM i on Power Systems!'
The optional last two parameters of %SCANRPL let you specify the start and end positions of the string you want to scan, so you don't need to replace all occurrences of the pattern if you don't want to.
Now that, my fellow string-manipulating friends, is cool.
as/400, os/400, iseries, system i, i5/os, ibm i, power systems, 6.1, 7.1, V7, V6R1
|Last Updated on Wednesday, 15 June 2011 12:59|