05
Tue, Nov
5 New Articles

Practical RPG: More BIFs

RPG
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Built-in functions (BIFs) are powerful on their own, but together they can perform some fantastic feats!

 

In a previous article, we touched on how we can use built-in functions (BIFs) in I/O operations, a subtle but potent result of the syntactical enhancements in RPG. Using BIFs (and other expressions) in I/O operations reduces code complexity by removing work variables. Another way to reduce code complexity is just to remove lines of code. This article provides an example of how combining BIFs can do just that.

The Problem with Data

The focus of this article is that old bugaboo: dirty data. No matter what you do, you can get dirty data. It might be an unprintable character in a description or a comma in a number or a dash in a zip code. Users like to put things in their data that make them a little more human readable, but unfortunately human readability doesn't always translate well to computers. When that happens, we find ourselves writing code to strip those characters out.

 

In the bad old days of RPG, this sort of cleanup involved MOVEA, a couple of indexes, and a lot of looping. It wasn't pretty, and the code was typically messy and prone to error. Let's take a simple example in which we want to remove the following characters: apostrophes, quotation marks, ampersands, and hashtags. In this example, we're simply going to remove them entirely from the string. Another option would be to replace them with a specific character, which would require a single BIF. However, for this example I want to show you how we can chain two BIFs together, so we're not just going to replace the offending characters but instead entirely remove them.

 

Let's start with the original RPG III code. You've probably done code like this a million times in the past.

 

   E                 WK1       30 1

   E                 WK2       30 1

   C*

   C      *ENTRY   PLIST

   C               PARM          IFIELD 30

   C*

   C               MOVEAIFIELD   WK1

   C               Z-ADD*ZERO     X      30

   C               Z-ADD*ZERO     Y      30

   C      1         DO   30       X

   C      WK1,X     IFNE *BLANK

   C      WK1,X     ANDNE'/'

   C      WK1,X     ANDNE'-'

   C               ADD 1         Y

   C               MOVE WK1,X     WK2,Y

   C               ENDIF

   C              ENDDO

   C*

   C               MOVEAWK2       IFIELD

   C      IFIELD   DSPLY

   C               MOVE *ON       *INLR    

 

The code is straightforward, although due to the simple opcodes and the columnar nature of RPG III, it's not necessarily obvious. The function of this program (and the programs that follow) will be to strip periods, slashes, and embedded blanks from the input parameter and return the result. For debugging purposes, before we exit we display the result. The code to do this employs an obsolete opcode and some basic array manipulation. The input field IFIELD is moved into the source array WK1 using MOVEA. The program then loops using two indexes: X is the source index, Y is the target index. As the X index is incremented, each position in the source array is checked for one of the invalid characters. If it is not any of those, the target index is incremented and the character is moved into the target array WK2. After the loop is done, the target array is moved back into the input parameter to be passed back to the caller, and finally for debug purposes the formatted string is displayed.

 

Note the use of the MOVEA opcode. Since this opcode is unavailable in RPG /free, you need to be a bit more creative to get it to work. Primarily, it involves a data structure and the OVERLAY keyword. This gets around the MOVEA limitation. You can find the V5R4-level code below, although I don't intend to go through it in much detail. In many ways, the code (especially the FOR loop) is just a slightly modernized version of the RPG III code. The one major change would be the data structure named "data"; it allows me to reference the same memory as both a 30-character field named myField and a 30-position array named aField. Other than that, the code is pretty self-explanatory.

 

     d data         ds

     d   myField           1     30

     d   aField                  1   dim(30) overlay(data)

 

     d aWork         s             1   dim(30)

     d x             s            3u 0

     d y             s             3u 0

 

     d DATASCRUB   pr

     d iField                    30

 

     d DATASCRUB   pi

     d iField                    30

 

     /free

 

      myField = iField;

      y = 0;

      clear aWork;

      for x = 1 to 30;

       if aField(x) <> ' '

         and aField(x) <> '/'

         and aField(x) <> '-';

         y += 1;

         aWork(y) = aField(x);

       endif;

      endfor;

 

      aField = aWork;

      iField = myField;

 

      dsply myField;

      *inlr = *on;

 

     /end-free

 

You'll note that I specifically said V5R4; that's because I have a prototype for the mainline. That's required, and even has to match the program name. I've always been uncomfortable with the idea that inside program MYPGM I have to have a line of code that has the literal value MYPGM in it; it's always an opportunity for yet one more programming mistake. Thankfully, that particular restriction has been relaxed quite a bit in later releases. Combine that with the new more powerful APIs, and the line count goes down dramatically. So let's finish up the article with the lean, mean V7.1 version of the program.

 

     d               pi

     d iField                    30

 

     /free

   iField = %scanrpl(' ':'':%xlate('/-':' ':iField));

 

      dsply iField;

      *inlr = *on;

     /end-free

 

This is much more like it. In the D-specs, the prototype is gone, leaving only the procedure interface, which takes the place of the *ENTRY PLIST in older code. As you can see, pretty much all of the D-specs are gone, because we don't need any array manipulation; we use the new BIF %scanrpl to do the yeoman's part of the work with some help from the %xlate BIF. Let me take some time to walk you through that one single line of code.

 

First, we look at the %xlate BIF that takes up the right side of the line. That BIF takes three parameters (it also has an optional fourth parameter that we won't using in this example). The last parameter is the string to translate, while the first two identify how to translate it. The first parameter is a list of characters that will be translated, and the second parameter defines what to translate each of those characters to. This is a one-to-one relationship: each character in the first string must have a matching position in the second string (be careful with this; if your second parameter doesn't have as many characters as the first, the extra characters in the first parameter are ignored). This is a very flexible design; we sometimes see this BIF used to translate lowercase letters to uppercase using the parameters 'abc…xyz' (with the ellipsis representing the other 20 letters) and 'ABC…XYZ' in the second parameter. In this case, though, we're doing something a little different: we're converting the characters we want to remove to spaces. So the %xlate returns the original string with all unneeded characters replaced with spaces.

 

Now we see how chaining BIFs works: we take the result of the %xlate BIF and use it as the input parameter to the new %scanrpl BIF. %scanrpl takes the contents of the third parameter and replaces every instance of the first parameter with the second parameter. This can be anything from a single character to a whole phrase; it's a great way to perform substitutions of all kinds, including placeholders for formatted data. But in this case, we do something just a little clever: we replace every single blank with a zero-length string, which effectively removes the blank from the source string. Clever indeed!

 

So this single line of code does two things: first, it replaces all dashes and slashes with spaces; then it removes all spaces. This single line does all the work we did with our original array work, and thus "ABC-DEF GHI/JKL" comes out as "ABCDEFGHIJKL". No arrays, no indexes, no work variables (all of which are opportunities for programming mistakes). Perfect!

 

It's probably a good idea to take a little time to familiarize yourself with any new BIFs (or BIFs that are new to you!) and see if you can incorporate them into your algorithms. And keep coming back here for more BIFs! Happy programming!

 

 

Joe Pluta

Joe Pluta is the founder and chief architect of Pluta Brothers Design, Inc. He has been extending the IBM midrange since the days of the IBM System/3. Joe uses WebSphere extensively, especially as the base for PSC/400, the only product that can move your legacy systems to the Web using simple green-screen commands. He has written several books, including Developing Web 2.0 Applications with EGL for IBM i, E-Deployment: The Fastest Path to the Web, Eclipse: Step by Step, and WDSC: Step by Step. Joe performs onsite mentoring and speaks at user groups around the country. You can reach him at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Joe Pluta available now on the MC Press Bookstore.

Developing Web 2.0 Applications with EGL for IBM i Developing Web 2.0 Applications with EGL for IBM i
Joe Pluta introduces you to EGL Rich UI and IBM’s Rational Developer for the IBM i platform.
List Price $39.95

Now On Sale

WDSC: Step by Step WDSC: Step by Step
Discover incredibly powerful WDSC with this easy-to-understand yet thorough introduction.
List Price $74.95

Now On Sale

Eclipse: Step by Step Eclipse: Step by Step
Quickly get up to speed and productivity using Eclipse.
List Price $59.00

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: