Volume 9, Number 8 -- March 4, 2009

A Bevy of BIFs: %XLATE and %REPLACE

Published: March 4, 2009

by Jon Paris

The %XLATE and %REPLACE text replacement built-in functions (BIFs) are often confused, and part of that confusion may be the result of wishful thinking on the part of RPGers frustrated with the limitations of %XLATE. Just as with the %SCAN and %CHECK BIFs that I discussed in an earlier tip, the major difference between %XLATE and %REPLACE is that %XLATE operates on individual characters and %REPLACE operates on strings.

Before we study %REPLACE, let's quickly review the function of %XLATE.

%XLATE( from : to : input {: startpos} )

The function of %XLATE is to search the input string for any instances of the individual characters contained in the from string and to replace them with the corresponding character in the to string. So in this example:

result = %XLATE( 'ABC': 'XYZ': source);

Any occurrences of the character 'A' in the source string will be replaced by 'X', 'B' by 'Y', and 'C' by 'Z'. So if we assume that source contains '123ABC789' before the operation, afterward the result will contain '123XYZ789'.

The mistake that many programmers make is to think that %XLATE is replacing the combination of characters. In other words, in the above example, the string 'ABC' is being replaced. It is, but only as the result of the characters 'A', 'B', and 'C' being individually replaced. Had the input contained 'ABD', it would have been converted to 'XYD'. This misconception can result in code being written that will "almost" work and that may under test conditions appear to work correctly.

Suppose that we want to replace any occurrence of the character string '/*' with '&&'. The programmer might code:

result = %Xlate('/*': '&&': source);

But while this may appear at first glance to work, it will not only convert all instances of '/*' but, because it is operating on a character by character basis, it will also translate individual '/' or '*' characters--probably not what was wanted. The following code demonstrates this:

     D source          s             36a
     D result          s             36a

D from            s              5a   Inz('/*') varying
D to              s              5a   Inz('&&') varying


// Demonstrate effect of using the %Xlate approach
// - Results in '&& Leave &these& and &these& &&'

source = '/* Leave /these/ and *these* /*';
dsply ('Source: ' + source);

result = %Xlate(from: to: source);
dsply ('Result:' + result);

While it would be nice if RPG did indeed have a built-in function that operated as desired (i.e., to replace one string with another), it actually requires a combination of the %SCAN and %REPLACE BIF's to achieve this.

The basic syntax for %REPLACE is shown here:

%REPLACE( replacement : source { :startpos {: length to replace}} )

The code below demonstrates how these BIFs can be used in combination to achieve the desired functionality. The start position for the string to be replaced is obtained by an initial %SCAN (A). It is then used to specify the start position for the %REPLACE operation (B). On the subsequent scan operations, the optional start parameter (C) is used to skip past the portion of the string that has already been processed.

D result          s             36a

D from            s              5a   Inz('/*') varying
D to              s              5a   Inz('&&') varying

D position        s              5i 0
D start           s              5i 0


// This is a valid approach to handling character strings
//  - It will result in '&& Leave /these/ and *these* &&'

result = '/* Leave /these/ and *these* /*';
(A)  position = %Scan( from: result);

DoW position > 0;
(B)  result = %Replace( to: result: position);
       start = position + 1;
(C)  position = %Scan( from: result: start);

dsply ('Result:' + result);

While %REPLACE may not operate exactly as we'd have liked it to, it does have a number of nice features. For one, the length of the replacement string does not have to match the length of the text to be replaced. In such cases, the optional fourth parameter is used to specify the number of characters to be replaced. This makes the BIF very useful in mail-merge type operations where you want to replace a text marker with a variable amount of text. For example, the base text might include a marker like "&Name", which we are going to replace with the customer's name. So we might code the %REPLACE operation like this:

result = %Replace( custName: result: startPosition: 5);

This will cause the BIF to replace "&Name" (five characters) with the content of custName. Once again variable length fields are useful with this BIF. In fact, the above code assumes that custName is a variable length field; if it were not we would have had to code %TrimR(custName) as the parameter to avoid inserting potentially large numbers of blanks.

There is a lot more we could say about %REPLACE, but the intent of this tip is to clarify the differences between %XLATE and %REPLACE. Perhaps we'll return to the topic on another occasion.

Jon Paris is one of the world's most knowledgeable experts on programming on the System i platform. Paris cut his teeth on the System/38 way back when, and in 1987 he joined IBM's Toronto software lab to work on the COBOL compilers for the System/38 and System/36. He also worked on the creation of the COBOL/400 compilers for the original AS/400s back in 1988, and was one of the key developers behind RPG IV and the CODE/400 development tool. In 1998, he left IBM to start his own education and training firm, a job he does to this day with his wife, Susan Gantner--also an expert in System i programming. Paris and Gantner, along with Paul Tuohy and Skip Marchesani, are co-founders of System i Developer, which hosts the new RPG & DB2 Summitconference. Send your questions or comments for Jon to Ted Holt via the IT Jungle Contact page.


A Bevy of BIFs: %SCAN and %CHECK

A Bevy of BIFs: Getting a Date is Easy with %Date

A Bevy of BIFs: Look Up to %LookUp

                     Post this story to del.icio.us
               Post this story to Digg
    Post this story to Slashdot

Sponsored By

                                                 IBM® System i® Data Access Made Easy

                                              · Complete management access to critical data
                                              · Easy to use by IT and end users
                                              · Automated data access and display
                                              · Comprehensive BI package: reports, tables,
                                                 key performance indicators, and dashboards
                                              · System i-centric for real-time data analysis
                                              · Expert support and training

Click here for a FREE Information Kit!

Senior Technical Editor: Ted Holt
Technical Editor: Joe Hertvik
Contributing Technical Editors: Edwin Earley, Brian Kelly, Michael Sansoterra
Publisher and Advertising Director: Jenny Thomas
Advertising Sales Representative: Kim Reed
Contact the Editors: To contact anyone on the IT Jungle Team
Go to our contacts page and send us a message.

Sponsored Links

System i Developer:  RPG & DB2 Summit in Orlando, April 15-17 for 3 days of serious training
ARCAD Software:  FREE Webinar and White Paper, How ALM Can Save You Money
COMMON:  Join us at the 2009 annual meeting and expo, April 26-30, Reno, Nevada


IT Jungle Store Top Book Picks

Easy Steps to Internet Programming for AS/400, iSeries, and System i: List Price, $49.95
Getting Started with PHP for i5/OS: List Price, $59.95
The System i RPG & RPG IV Tutorial and Lab Exercises: List Price, $59.95
The System i Pocket RPG & RPG IV Guide: List Price, $69.95
The iSeries Pocket Database Guide: List Price, $59.00
The iSeries Pocket Developers' Guide: List Price, $59.00
The iSeries Pocket SQL Guide: List Price, $59.00
The iSeries Pocket Query Guide: List Price, $49.00
The iSeries Pocket WebFacing Primer: List Price, $39.00
Migrating to WebSphere Express for iSeries: List Price, $49.00
iSeries Express Web Implementer's Guide: List Price, $59.00
Getting Started with WebSphere Development Studio for iSeries: List Price, $79.95
Getting Started With WebSphere Development Studio Client for iSeries: List Price, $89.00
Getting Started with WebSphere Express for iSeries: List Price, $49.00
WebFacing Application Design and Development Guide: List Price, $55.00
Can the AS/400 Survive IBM?: List Price, $49.00
The All-Everything Machine: List Price, $29.95
Chip Wars: List Price, $29.95

The Four Hundred
IBM Adds i Shops to Expanded p Shop Trade-In Deal

IBM and Resellers Do the iLoyalty Blitz

Server Sales Slumped As 2008 Stumbled to the Holidays

Mad Dog 21/21: That'll Teach 'Em

Healthcare and Utilities Lead Vertical Markets in IT Spending

Four Hundred Stuff
xTuple Reports Strong Growth of Open Source ERP

LaserVault Shrinks System i Backups with Data De-Duplication

Paglo Adds 'NetFlow' to IT Search Service

Vision Debuts 'PowerPacks' Product Bundles

WIS:DOM Hooks Up with ACOM

Four Hundred Monitor
Four Hundred Monitor's
Full iSeries Events Calendar

System i PTF Guide
February 28, 2009: Volume 11, Number 9

February 21, 2009: Volume 11, Number 8

February 14, 2009: Volume 11, Number 7

February 7, 2009: Volume 11, Number 6

January 31, 2009: Volume 11, Number 5

January 24, 2009: Volume 11, Number 4

TPM at The Register
AMD: 'At heart, we're a design company'

EMC facing DoJ probe

Gartner: PC sales, except netbooks, to slump in 2009

Citrix taps VMLogix for fake server jukeboxing

IDC chops 2009 IT spending forecasts (again)

Sun powers Niagara hypervisor update with IBM speed boast

HP iron still haunted by ghost of Compaq

Novell spills sales after pipe breakage

Big Blue flaunts Meltdown-proof coating

VMware, Novell hatch virtual appliance scheme

Microsoft plays with small, sleepy servers

Server sales cratered in Q4, says IDC

Super Micro squeezes four servers into one chassis

Gartner: Global IT spending will rise in 2009 (slightly)


System i Developer

Printer Friendly Version

A Bevy of BIFs: %XLATE and %REPLACE

Send Messages Unto Others

Admin Alert: Things I Learned About IBM Maintenance Contracts

Four Hundred Guru


From the IT Jungle Forums
Insert via Java

iSeries Access for Web

Mimix installation and configuration docs

EDI Inovis Programmer - Heavy Duty Problem Solver - Anytime

Data Queues vs. MQ Series: Performance

Removing blanks from a CL Variable


Subscription Information:
You can unsubscribe, change your email address, or sign up for any of IT Jungle's free e-newsletters through our Web site at http://www.itjungle.com/sub/subscribe.html.

Copyright © 1996-2009 Guild Companies, Inc. All Rights Reserved.
Guild Companies, Inc., 50 Park Terrace East, Suite 8F, New York, NY 10034

Privacy Statement