21
Sat, Dec
3 New Articles

Simple Tasks in RPG IV Made Simpler

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

One thing we need to do as programmers is keep current on our RPG IV skills. By "keeping current," I mean knowing what features of the language are available and what they can do for us.

RPG IV is an interesting language. In other languages, such as C and Java, the languages themselves do very little; you have If, Then, Else, CASE, Do, and the ability to call subprocedures or functions. To add functionality to the language, you need to buy an add-on library or hope the language manufacturer provides one with your compiler.

My own RPG xTools add-on library consists of about 200 prewritten and ruggedly tested RPG IV subprocedures. They act just like RPG IV's built-in functions. But RPG IV has a lot of its own functions that, in other languages, would normally only be available in add-on libraries.

When asked about the best way to do a simple task, I often get the Rube Goldberg solution along with the question. For example: "How do I...? Here's what I did." They ask the question and then give me a clumsy answer. Not a bad answer, mind you, just a bit clumsy. RPG IV has so many ways to do some things that it's easy to overlook an easier method when attempting to do something.

So this week I am presenting some typical questions along with several solutions: one or two clumsy solutions and one or two straightforward solutions. All solutions will work in all situations, but the straightforward solutions are a bit cleaner than the others. Oh, yes, I expect to hear from you in the discussion forum as to why your solution is better than the straightforward solutions I present in this issue. That's what a free exchange of ideas is for, so let's get started.

How Do I Left-Justify Text Within a Character Field?

Clumsy Solution 1:

D Start           S              5U 0
D End             S              5U 0
D Len             S              5U 0
D MyValue         S            300A   Inz('    01234567')

C     ' '           Check     myValue       Start
C     ' '           CheckR    myValue       End
C                   eval      Len = (End - Start) + 1
C                   eval      myValue = %subst(myValue:Start:Len)

This solution uses a typical application of the %SUBST built-in function to extract just the data within the original MYVALUE field and move it, left-justified, into itself via the EVAL opcode.

Clumsy Solution 2:

D Start           S              5U 0
D MyValue         S            300A   Inz('    01234567')

C     ' '           Check     myValue       Start 
C                   eval      myValue = %subst(myValue:Start)

This solution uses the assumption ability of the %SUBST built-in function. If no length parameter is specified, this code assumes you want to use all data in the field, from the starting location through the end of the field. The second solution is much cleaner than the first solution, but it's still a bit clumsy compared to the straightforward solution.

Straightforward Solution:

D MyValue         S            300A   Inz('    01234567')

C                   eval      myValue = %TrimL(myValue)

In this solution, we use the %TRIML (trim left) built-in function to remove left-side blanks from the field's value. Since EVAL copies data left-justified, if we truncate the leading blanks, the combination of %TRIML and EVAL cause the value to be left-justified. Clean, clear, and only one line of code!

How Do I Right-Justify a Value in a Character Field?

Right-justification is a bit more challenging than left-justification. Often, people don't even know the solution exists, let alone how to apply it.

Clumsy Solution:

D Start           S              5U 0
D Start2          S              5U 0
D End             S              5U 0
D Len             S              5U 0
D MyValue         S            300A   Inz('    01234567')

C     ' '           Check     myValue       Start
C     ' '           CheckR    myValue       End
C                   eval      Len = (End - Start) + 1    
C                   eval      Start2 = (%size(myValue) - Len) + 1
C                   eval      %Subst(myValue:Start2) = 
C                                       %subst(myValue:Start:Len)

This solution is similar to the left-justify solution, but it uses %SUBST on both the left and right sides of the equals sign (=). By calculating the starting location for the data in the field, you can shift it to the right-justification location, provided you do the math correctly.

Straightforward Solution:

D MyValue         S            300A   Inz('01234567')

C                   evalR     myValue = %TrimR(myValue)

You knew it had to be that easy, right? The built-in function %TRIMR strips off trailing blanks for the value. Then, the EVALR (EVAL with right-justify) opcode copies the data, right-justified to the target field. So again, with one line of code, you can right-justify data within a field.

How Do I Convert Numeric to Character?

This has been problematic since RPG IV first came out. In RPG III and even in RPG III-style RPG IV code, you can simply use the MOVE opcode to convert between numeric and character; that hasn't changed a bit. But most people ask this question in the context of the EVAL opcode or the so-called "free-format" RPG IV syntax.

Clumsy Solution:

D CustNo          S              7P 0 Inz(3741) 

D MyDS            DS                  Inz
D  CstNbrA                       7A
D  CstNbr                        7S 0 Overlay(CstNbrA)
D First           S              5I 0
D Loc             S              5I 0

C                   eval      CstNbr = CustNo
C     '0'           Check     CstNbrA       First
C                   eval      Loc = 1    
C                   Dow       Loc < First
C                   eval      %Subst(CstNbrA : Loc : 1) = ' '
C                   eval      Loc = Loc + 1
C                   enddo

In this solution, the packed decimal field is copied into a zoned decimal subfield of the MYDS data structure. The CSTNBR field overlays the CSTNBRA field in that data structure. So when the value is copied from CUSTNO to CSTNBR, the field CSTNBRA contains '0003741'.

The CHECK opcode locates the first non-zero position on the left side of the CSTNBRA subfield. Then, the routine enters a DO loop that replaces the leading zeros with blanks. When the loop exits, the CSTNBRA subfield contains '___3741', which you must then left-justify or do whatever it is you need to do with it.

Straightforward Solution 1:

D CustNo          S              7P 0 Inz(3741) 
D CstNbrA         S              7A

C                   eval      CstNbrA = %TrimL(%EditC(CustNO:'Z'))

In this solution, the %EDITC built-in function is used to apply the 'Z' edit code to the numeric value in CUSTNO. Since %EDITC returns a character value with leading zeros replaced by blanks (that is, the leading blanks are also returned), I wrap the %EDITC built-in itself in another built-in function, %TRIML, to strip off leading blanks. The result is a left-justified numeric value stored in the CSTNBRA character field, as follows: '3741___'

If you need leading zeros to remain with the value, this second solution may be better for your situation:

Straightforward Solution 2:

D CustNo          S              7P 0 Inz(3741) 
D CstNbrA         S              7A

C                   eval      CstNbrA = %EditC(CustNO:'X')

In this solution, the lightly documented edit code 'X' is used. The 'X' edit code converts the numeric value to character with leading zeros, and that's all. So you end up with CSTNBRA containing '0003741'.

Straightforward Solution 3:

D CustNo          S              7P 0 Inz(3741) 
D CstNbrA         S              7A

C                   eval      CstNbrA = %Char(CustNO)

If you prefer a simple solution that doesn't have a lot of thinking behind it, use the %CHAR built-in function. This wonderful built-in function converts numeric values to character and strips off leading zeros, all in one action. The beauty of this built-in function is that it doesn't do anything extra that would need to be managed. If you simply want a numeric value in character format, which is often needed for CGI and EDI applications, %CHAR is the right choice for you.

After the EVAL operation is performed, the CSTNBRA field will contain the value '3741___'.

Suppose you have a field that contains a decimal. For example:

D Sales           S             11P 2 Inz(002133.50) 
D SalesA          S             15A

C                   eval      SalesA = %Char(Sales)

After this solution is performed, the field named SALESA will contain the value '2133.50' plus the trailing blanks, of course. That is, the %CHAR built-in function correctly inserts the decimal notation for the value; it does not insert thousands notation. Also, if the value is negative, a minus sign (-) is embedded for you automatically.

How Do I Convert Character to Numeric?

What about the other way around? What if you need to move a value that is stored in plain text to a numeric field? How do you get that to work?

Clumsy Solution:

D CustNo          S              7P 0 
D CSTNBRA         S             12A   Inz('  3741')
D ZEROS30         S             30A   Inz(*ZEROS)
D MyDS            DS                  Inz
D  Alpha                        30A 
D  Numeric                      30S 0

C                   evalR     Alpha = ZEROS30 + %TrimL(CSTNBRA)
C                   eval      CustNo = Numeric

In this solution, a literal containing 30 zeros is concatenated with the field containing the numeric value. The %TRIML built-in function is used to ensure that no leading blanks are detected. Then, the EVALR (EVAL with right-justify) opcode is used to cause the text to be copied to the ALPHA field, starting with the rightmost characters. That way, the leading zeros from ZEROS30 are truncated, filling the ALPHA field with a neat, zero-filled value. Then, using the NUMERIC subfield that overlays the ALPHA field within the data structure, the numeric value is copied to the packed field.

While I've attempted to make this as least clumsy as possible, it is still quite clumsy.

Straightforward Solution 1:

D CustNo          S              7P 0 
D CstNbrA         S              7A   Inz('3741')
D Sales           S             11P 2 
D SalesA          S              7A   Inz('1200.32')

C                   eval      CustNo = %int(CstNbrA)
C                   eval      Sales = %Dec(SalesA:11:2)

In this solution, the %INT built-in function is used to convert the plain-text value in the CSTNBRA character field into a numeric value.

This solution uses the %DEC built-in function to convert the plain text to numeric. The primary difference between %DEC and %INT is that %DEC allows the use of decimal places, whereas %INT only works with whole numbers (integers).

One major problem with this solution is that it doesn't appear until V5R2. A year ago, I wouldn't even have shown this solution since virtually no one was even on V5R1 at that point. But today, most people are moving off of OS/400 V4 onto V5R2 (often skipping V5R1 in the process). So I believe it to be a viable solution.

There are a couple of other options as well, however.

Straightforward Solution 2:

H  BNDDIR('XTOOLS') 
D/INCLUDE XTOOLS/QCPYSRC,CHARTONUM 
D CustNo          S              7P 0 
D CstNbrA         S              7A   Inz('3741')
D Sales           S             11P 2 
D SalesA          S              7A   Inz('1200.32')

C                   eval      CustNo = CharToNum(CstNbrA)
C                   eval      Sales = CharToNum(SalesA)

In this solution, the RPG xTools' CHARTONUM procedure is used to convert between character and numeric. CHARTONUM doesn't care what format the input value is in; it can be an integer or a decimal value in plain text, and it converts properly. The benefit of CHARTONUM is that it works as far back as V4R4 and works just as fast as or faster than the built-in functions that are available in V5R2.

Straightforward Solution 3:

H  BNDDIR('QC2LE') 
D/INCLUDE RPGLAB/QCPYSRC,CPROTOS
D CustNo          S              7P 0 
D CstNbrA         S              7A   Inz('3741')

C                   eval      CustNo = atoll(CstNbrA)

This solution is a bit more limited, but it's actually the preferred technique when whole numbers (integers) are being converted. It converts the plain-text numeric value into an integer and then assigns it to the CUSTNO field.

The solution uses the C language runtime library. The atoll function converts a text string containing a number into a numeric integer value. The EVAL copies that value to the target, and you have the conversion. The downside to this technique is that it will not work when decimal values are involved. It only works with whole numbers.

Taking It Easy

The bottom line is that programming with RPG IV can be as complicated as you want to make it, or it can be easy. I choose the easy road and embrace the simple life. I hope you will, too.

Bob Cozzi is a programmer/consultant, writer/author, and software developer. His popular RPG xTools add-on subprocedure library for RPG IV is fast becoming a standard with RPG developers. His book The Modern RPG Language has been the most widely used RPG programming book for more than a decade. He, along with others, speaks at and produces the highly popular RPG World conference for RPG programmers.

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: