20
Sat, Apr
5 New Articles

Centering a String of Text

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

StrCenter() is an RPG IV subprocedure that takes any uncentered text variable (or string) and returns the centered text. Hence, the name StrCenter—great for centering text on displays and reports!

Since the introduction of RPG IV with V3R1, nothing other than a few syntactical changes warranted converting my RPG III code. But, with V3R2’s addition of subprocedures and then V3R7’s pointers and memory management for such things as unbounded arrays, I can now justify code conversion. While pointer manipulation and memory management operations are quite interesting topics, this article will focus on the much more interesting topic of subprocedures. Subprocedures can be described as well- contained (modular) logic that deals with a specific problem (limited scope) and has a well- defined set of arguments (interface) that describes only enough about the nature of the subprocedure to properly utilize it. This definition enables global usage of a subprocedure without being concerned about how a particular application uses it. In many respects, a subprocedure is like a well-constructed /COPY source member, except that, with subprocedures, we promote binary—not source—reuse, and we can pass parameters (arguments) to it. But how could subprocedures be employed in my programs, you ask?

Assume you have a report or inquiry in which some text must be centered for proper presentation to the user. For example, say the Customer Service department has requested that you create an inquiry screen in which, by selecting a customer name from a list and pressing Enter, the user can access a full-screen panel that shows the name of the customer at the top. Since customer names can be very short or very long, a subprocedure such as StrCenter() ensures the name will always be centered, providing a professional look to the panel.

In Figure 1, I have used two cases to show the versatility of subprocedures in general and StrCenter() in particular.

Note that our subprocedure, StrCenter(), accepts two parameters or arguments: (1) a reference to the string to be centered and (2) the length within which to center the string.

This subprocedure will return the centered text to the receiver variable of our assignment in the EVAL statement (in this case, Title).

In Case 1, the same variable passed to StrCenter() as the first argument is also defined as the receiver. In this case, the second argument passed is the %SIZE of Title (40 bytes). Case 2 shows Title being defined as the receiver for the StrCenter() subprocedure results. MyText is passed as the referenced variable text to be centered in Title, with a numeric literal as a constant (40) passed as the second argument to the subprocedure .

(For more information about how to compile, see the sidebar “Compiler Directives.”)

The PR statement (Figure 2, Label B), or prototype definition statement, identifies and defines any value to be returned by the subprocedure. This must be the maximum length of receiver variable that can be returned by the subprocedure. I have limited this to a maximum string length of 256 characters.

Immediately following this statement are the parameters that will be passed to the StrCenter() subprocedure (Figure 2, Labels C and D). These can be given names or not; they are inconsequential to our discussion. The compiler that creates our program module is interested only in the number and type of parameters, not the names. Since one of the main benefits of subprocedures is hiding the implementation details (such as subprocedure local variable names) from the user application, we will not concern ourselves with what those names might be. If you want to review the implementation details of the StrCenter() subprocedure, see “Subprocedures: A Step in the Right Direction!” also in this issue.

Figure 3 shows a trivial program that uses this function to center text defined in MyText as left-justified. The result of the centering function is displayed with the DSPLY RPG op code.

As you can see, by using the StrCenter() subprocedure, you can ensure consistency in handling text-centering functions and avoid programmer resources being expended on recoding the same logic over and over again. But don’t stop there; you can write many other subprocedures to save your programmers from wasting time recoding commonly required functions. The primary obstacle that we RPG programmers must overcome is the unspoken principle of “If I didn’t build it, it must not be any good.” I must confess that I too have been guilty of this sin. But since I have been extensively utilizing subprocedures and service programs, I have come to accept (and blindly so) that I must depend upon others for the prebuilt components required to meet productivity objectives in today’s world. And, if you are getting those components off the shelf, you may not be able to review the source code unless you buy it (usually, at quite a premium). So jump on the bandwagon! But don’t just build subprocedures; become a user as well!

D Title S 40A INZ(‘Very, very, long text’)
D MyText S 30A INZ(‘Short text’)

CASE 1: EVAL Title = StrCenter(Title : %SIZE(Title))
Before StrCenter (): |Very, very, long text |
After StrCenter(): | Very, very, long text |
CASE 2: EVAL Title = StrCenter( MyText : 40)
Before StrCenter(): |Short text |
After StrCenter(): | Short text |

Figure 1: Using StrCenter()

** Compiler Directives*------------------------------------------------------------------

/If Not Defined( StrCenterHCopied )
/Define StrCenterHCopied
/Else
/Eof
/EndIf

** Prototype for StrCenter () Subprocedure

*D StrCenter PR 256A OPDESC

D {Text or String passed to be centered} 256A Options(*VARSIZE)

D {Size of Receiver Variable } 5P 0 CONST

*-

Figure 2: StrCenter() compiler directives and prototype

*=================================================================

* To compile:

*

* CRTBNDDIR BNDDIR(XXX/STRLIB)

* ADDBNDDIRE BNDDIR(XXX/STRLIB) OBJ((XXX/STRCENTER *MODULE))

* CRTRPGMOD MODULE(XXX/TEST) SRCFILE(XXX/QRPGLESRC)

* CRTPGM PGM(XXX/TEST) MODULE(XXX/TEST) +

* BNDDIR(XXX/STRLIB)

*

*=================================================================

/COPY SYSINC,StrCenterH

*

D MyText S 30A INZ(‘Uncentered Text’)

D Title S 40A

*

C MyText DSPLY

* Produces output |Uncentered Text |

C EVAL Title = StrCenter( MyText:%SIZE(Title))

C Title DSPLY

* Produces output | Uncentered Text |

C EVAL *INLR = *ON

Figure 3: A Program Using StrCenter()

Compiler Directives

The compiler directives, shown in Figure 2, Label A, are specified at the top of the source for my prototype definition. I have defined a compiler condition variable, StrCenterHCopied, that will be created when the program reads the first /COPY that includes this definition. This technique avoids compiler errors that would result if another subprocedure or module had already prototyped it for compilation. As indicated with the /Eof directive, once the condition variable StrCenterHCopied has been defined, the compiler will receive an /Eof indication each time it attempts to copy the source for the prototype into the current compile text. Without these directives, /COPY directives for the same member would result in duplicate declarations for prototyped variables and thus end with compiler errors. As shown in the compile instructions, the StrCenter() subprocedure should be compiled and placed in a binding directory for string library (STRLIB) subprocedures. You can place your subprocedure in the binding directory by first creating the directory and then adding the StrCenter() module to it, as shown in the compile instructions in Figure 3.

By doing this, you will simplify binding when many modules defined in STRLIB are required. Then, all you have to do is define the binding directory, as I did in Figure 3’s Create Program (CRTPGM) command, rather than list each module separately in the CRTPGM MODULE parameter.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

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: