24
Tue, Dec
1 New Articles

The CL Corner: Create Reusable Code

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

Are you creating commands to improve your productivity?

 

This article is the first of several related to creating your own user CL commands. We will start with a simple command definition and then enhance the command with various features in order to demonstrate how to incorporate these extensions within your own commands. But first we need a command scenario.

 

In a CL program, have you ever wanted to concatenate a decimal value to a character string and then display the result? That is, take a character string such as 'The cost is $', append a decimal value such as 1.23, and then display a result of "The cost is $1.23" as attempted in the following program?

 

Pgm                                                         

Dcl        Var(&Number)   Type(*Dec)  Len(6 2)  Value(1.23)  

                                                    

SndPgmMsg  Msg('The cost is $' *Cat &Number)                 

 

EndPgm

 

If so, you found out quickly enough that the *Cat built-in (along with *BCat and *TCat) does not support the concatenation of character and decimal operands. Suppose you attempt to compile the previous source as program SAMPLE using the following command:

 

CRTBNDCL PGM(SAMPLE)

 

This will result in the compile failures CPD0712 – Operand does not have valid type for operator, and CPD0711 – Operands in expression not same type. The CL concatenation built-ins only support character strings. Adding an intermediate character conversion, as shown below with the &Char variable, gets you close, but not quite to the desired result.

 

Pgm                                                        

Dcl        Var(&Number)   Type(*Dec)  Len(6 2)  Value(1.23)  

Dcl        Var(&Char)     Type(*Char) Len(10)                 

                                                           

ChgVar     Var(&Char) Value(&Number)                       

SndPgmMsg  Msg('The cost is $' *Cat &Char)                 

 

EndPgm

 

Rather than "The cost is $1.23", you have "The cost is $0000001.23". This is due to the CHGVAR command, as documented, right-justifying the resulting character value of &Number and padding on the left with zeros. For some, this might be good enough; for others, the leading zeroes in the resulting message will just not be acceptable. To remove the leading zeroes and left-justify the value of the &Char variable, you might then change the program as shown below.

 

Pgm                                                             

Dcl        Var(&Number)   Type(*Dec)  Len(6 2)  Value(1.23)     

Dcl        Var(&Char)     Type(*Char) Len(10)                   

                                                                

Dcl        Var(&Char_Siz) Type(*UInt) Value(10)                 

Dcl        Var(&Char_Pos) Type(*UInt)                            

Dcl        Var(&Char_Rem) Type(*UInt)                            

                                                                

ChgVar     Var(&Char) Value(&Number)                            

                                                                 

DoFor      Var(&Char_Pos) From(1) To(&Char_Siz)             

           If Cond(%sst(&Char &Char_Pos 1) *EQ '0') +       

              Then(Iterate)                                 

           Else Cmd(Leave)                                  

           EndDo                                            

                                                            

ChgVar Var(&Char_Rem) Value((&Char_Siz + 1) - &Char_Pos)      

ChgVar Var(&Char) Value(%sst(&Char &Char_Pos &Char_Rem))  

                                                            

SndPgmMsg  Msg('The cost is $' *Cat &Char)                  

                                                            

EndPgm                                                       

 

The IF test within the DOFOR is checking for leading zeros within the &Char variable by examining each single byte character of the &Char variable one character at a time. Variable &Char_Pos identifies the character currently being examined and is the VAR control variable for the DOFOR loop. If a leading zero is found, the routine uses the ITERATE command to move to the next character of the &Char variable. When a non-zero character is encountered, the LEAVE command is run and the DOFOR is exited.

 

When the DOFOR loop is exited, the program left-adjusts all remaining characters of the &Char variable, starting with the first non-zero character found, and then blank pads any remaining positions of the &Char variable. To do this, the variable &Char_Rem is used to represent the number of significant characters REMaining in the &Char variable after trimming any leading zeros. Upon setting the correct value of &Char_Rem, the CHGVAR command (with a keyword VAR value of the full variable name &Char and a keyword VALUE parameter value defining the relevant substring of &Char) is used to left-adjust the significant characters of &Char and blank pad any positions of &Char beyond the %sst specified length.

 

Because CL variable &Number is declared with two decimal positions, the IF test will always find a non-zero value— the decimal point if nothing else. Note, though, that handling negative values for the &Number variable will require an additional check if we want to trim leading zeros, as the negative sign precedes the leading zeros when returned from the initial CHGVAR command. This check for negative values will be handled in a subsequent article. Compiling and running the sample program using a range of &Number values, the program displays the following messages for various non-negative &Number values.

 

&Number          Message displayed

0                The cost is $.00

1.23             The cost is $1.23

1234.56          The cost is $1234.56

 

This is much better! It's also likely that this logic, left-adjusting and removing leading zeros, can be useful to many other CL programs. To share this logic, you could copy this DOFOR routine to the other programs or make it into a subroutine and use the CL INCLUDE command to include the logic into multiple programs, but you will most likely need to tweak this code (or the other programs) as the CL character variable is unlikely to be called &Char in all of these other programs. A better approach might be to create a user command that implements this logic.

 

Before going any further, I will point out that actually a "better" solution, for this specific scenario, might be to utilize the message-handling support of the i operating system in formatting the value of the &Number variable:

 

1. Create a message file (or use an existing message file) with this command:

 

CrtMsgF MsgF(MyLib/MyMsgs)

 

2. Add a message description with a message replacement variable definition based on the CL &Number variable:

 

AddMsgD MsgID(MSG0001) MsgF(MyLib/MyMsgs) +

Msg('The cost is $&1') Fmt((*Dec 6 2))

 

3. Send this message as shown below:

 

Pgm                                                          

Dcl        Var(&Number) Type(*Dec)  Len(6 2)  Value(1.23)    

Dcl        Var(&Char)   Type(*Char) Len(4) +                 

Stg(*Defined) DefVar(&Number)                   

 

SndPgmMsg  MsgId(MSG0001) MsgF(MyLib/MyMsgs) MsgDta(&Char)   

 

EndPgm 

 

But as this article is intended to introduce you to the topic of creating your own highly flexible user commands, we'll bypass using the message-handler approach. Our command will be named Trim Left Characters, or TRMLFTCHR. The command definition is shown below.

 

Cmd        Prompt('Trim Left Characters')              

Parm       Kwd(Var) Type(*Char) Len(10) RtnVal(*Yes) + 

             Min(1) Prompt('Decimal value')                   

 

The TRMLFTCHR command defines one parameter, VAR. VAR is defined as a character variable with a length of 10 bytes and has a prompt display of "Decimal value". Because of the RTNVAL(*YES) specification on the PARM command, the TRMLFTCHR command can return an updated value using the VAR parameter. The MIN(1) specification indicates that the VAR parameter is required. To create the TRMLFTCHR command, you use the following Create Command (CRTCMD) command.

 

CRTCMD CMD(TRMLFTCHR) PGM(TRMLFTCHR) ALLOW(*IPGM *BPGM *IMOD *BMOD)

 

The CMD parameter of the CRTCMD command specifies the name of the command being created—TRMLFTCHR. The PGM parameter identifies the name of the command processing program (CPP) —in this case, also TRMLFTCHR. The ALLOW parameter specifies where the command can be run. The values shown indicate that the command can only be run in a CL program (ILE or OPM) or a CL ILE module (bound into a program). The TRMLFTCHR command cannot be run interactively (from, for instance, the command line) as the user of the TRMLFTCHR command must specify a CL variable name for the VAR parameter in order to receive the updated value. And a CL variable name is only possible within a program or module.

 

If your system is at V6R1 or later, you can specify the ALLOW parameter on the CMD statement of the command definition. Changing the CMD statement as shown below avoids the need to remember to re-specify the ALLOW parameter every time you need to recreate the command.

 

Cmd        Prompt('Trim Left Characters') ALLOW(*IPGM *BPGM *IMOD *BMOD)

 

The CPP, TRMLFTCHR, is shown below.

 

Pgm        Parm(&Char)                                        

Dcl        Var(&Char)      Type(*Char) Len(10)                

                                                               

Dcl        Var(&Char_Siz)  Type(*Uint) Value(10)              

Dcl        Var(&Char_Pos)  Type(*UInt)                        

Dcl        Var(&Char_Rem)  Type(*UInt)                        

                                                               

DoFor      Var(&Char_Pos) From(1) To(&Char_Siz)               

           If Cond(%sst(&Char &Char_Pos 1) *EQ '0') +         

              Then(Iterate)                                   

           Else Cmd(Leave)                                    

           EndDo                                              

                                                              

If         Cond(&Char_Pos *LE &Char_Siz) Then(Do)             

           ChgVar Var(&Char_Rem) +                            

                    Value((&Char_Siz + 1) - &Char_Pos)        

           ChgVar Var(&Char) +                               

                    Value(%sst(&Char &Char_Pos &Char_Rem))   

           EndDo                                              

Else       ChgVar Var(&Char) Value('0')                      

                                                             

EndPgm                                                       

 

As you can see, the CPP is essentially the logic we previously added to the application program. The two additions are defining the &Char variable as a parameter to the program (representing the VAR parameter of the TRMLFTCHR command) and an IF test upon exiting the DOFOR loop.

 

The new IF test is to cover the situation where there is no decimal point in the &Char value being processed and the value passed is all zeros. With the previous sample program, this will never occur as &Number is defined with two decimal positions and the initial CHGVAR command will return a character value of .00 for a &Number value of 0. However, other programs using the TRMLFTCHR command may be using a decimal variable declared with zero decimal positions—in which case, a numeric value of 0 will be represented by the character string "0000000000"—causing the CPP to iterate through the entire character string.

 

If all zeros are found in &Char, the DOFOR loop will exit with a &Char_Pos value greater than &Char_Siz (as &Char_Size is the DOFOR control variable specified with the TO keyword) or, to look at it another way, the value of &Char_Pos will be less than or equal to &Char_Siz if a non-zero value is encountered in the DOFOR loop and the LEAVE command is run. If a non-zero character is found, the same logic is applied as in the sample program: left-adjust and blank pad the significant characters of the &Char parameter. If only zero characters are found (the ELSE logic added to the CPP), the &Char variable is set to the single character value of '0' and then blank padded.

 

To create the TRMLFTCHR CL program use either of the following commands.

 

CRTBNDCL PGM(TRMLFTCHR)

or

CRTCLPGM PGM(TRMLFTCHR)

 

Returning to the earlier sample application program, we can now replace the logic associated with removing leading zeros and left-adjusting the result with the TRMLFTCHR command as shown below.

 

Pgm                                                         

Dcl        Var(&Number)   Type(*Dec)  Len(6 2)  Value(1.23) 

Dcl        Var(&Char)     Type(*Char) Len(10)                

                                                            

ChgVar     Var(&Char) Value(&Number)                        

TrmLftChr  Var(&Char)

                                       

SndPgmMsg  Msg('The cost is $' *Cat &Char)                  

 

EndPgm

 

This program, when run, will now display the message:

 

The cost is $1.23   

 

Any CL program needing to similarly display a character variable representing a numeric value can now use the TRMLFTCHR command—using the character variable name currently in use by the program for the VAR parameter and using any decimal variable value that can be represented in a 10-byte character variable. Not too bad. And certainly easily re-useable code by way of creating our own command.

 

There are, however, some limitations and considerations to the TRMLFTCHR command. One limitation is that it only supports 10-byte character variables for the VAR parameter. To verify this, change the definition of &Char in the sample application program from 10 bytes to 9. You will find that the compile fails with CPD0784 – Variable &CHAR for parameter VAR must be *CHAR, minimum length 10. Changing the definition of &Char in the sample program from 10 bytes to 11 will not result in a compile failure, but running the sample program may also not show the message you were expecting. This unexpected result will occur if the eleventh byte of the larger VAR variable is not a blank. As only the first 10 bytes of the VAR variable are being processed by the command, any value in the eleventh byte will not be left-adjusted or used while blank padding.

 

In the next article, we'll look at what's required to support a VAR CL character variable of virtually any length (and, in the third article of this series, we'll remove the qualifier "virtually").

More CL Questions?

Wondering how to accomplish a function in CL? Send your CL-related questions to me at This email address is being protected from spambots. You need JavaScript enabled to view it.. I'll try to answer your burning questions in future columns.

 

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: