23
Sat, Nov
1 New Articles

The CL Corner: Reduce Those Annoying Substring Operations

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

It's simple if you use *Defined storage.

 

A pet peeve of mine is going into a CL program to make some modifications and then encountering long sequences of Change Variable (CHGVAR) commands utilizing %substring operations in order to access, and then update, data stored in the local data area (LDA). The approach of using the LDA for program-to-program communication is, in many companies, done as an alternative to passing parameters to called or submitted programs. And over the years many of these companies have developed standards addressing how the LDA is laid out for this form of communication. Actual usage of the LDA, however, is often left to the individual developer in terms of implementation. In this article, we will review one possible approach to improve programming productivity when using the LDA.

 

For discussion purposes, we'll have a simple CL program that prompts the user for which of three reports to run. In addition to specifying what report to run, the user provides "from" and "to" dates for the content of the report and can choose to either run the report for a default state and company or override the state and company to be used for the report. The display file used, named LDA_DSPF, is shown below and can be created with the command CRTDSPF LDA_DSPF.

 

                                            CA03(03)              

                R PROMPT                                           

                  DEVICE        10   O  1  2                      

                  USER          10   O  1 13                      

                  DIVISION      40   O  1 24                      

                                        1 71DATE                  

                                            EDTCDE(Y)             

                                        2 35'Some Report'         

                                        2 71TIME                  

                                        4  2'State . . . . . .'   

                  STATE          2   B  4 20                      

                                        5  2'Company . . . . .'   

                  COMPANY        3   B  5 20                      

                                        7  2'Option  . . . . .'   

                  OPTION         1   I  7 20VALUES('1' '2' '3')   

                                            DSPATR(PC)            

                                        9  2'From (MMDDYYYY) .'     

                  FROMDATE       8   I  9 20                        

                                       10  2'To (MMDDYYYY) . .'     

                  TODATE         8   I 10 20                        

                                       23  2'F3=Exit'               

  

The values for many of the fields used for the display file can be found in the LDA of the job. The company has, for instance, defined some of the following fields to be available through the LDA (in reality, there are often many, many more):

 

Data                              Start Pos        Length        Data type

Device name                             1             10         Character

User name                              11             10         Character

Division name                          26             40         Character

Reporting organization                196              2         Character

Year                                  230              4         Character

State                                 234              2         Character

Company                               236              3         Character

Order invoice                         239              6         Character

From date (MMDDYYYY)                  301              8         Character

To date (MMDDYYYY)                    309              8         Character

 

Traditionally, the developer may have written the CL application program, named LDA_TRAD, as shown below.

 

Pgm                                                   

                                                     

DclF       File(LDA_DSPF)                            

                                                     

ChgVar     Var(&Device)   Value(%sst(*LDA   1 10))   

ChgVar     Var(&User)     Value(%sst(*LDA  11 10))   

ChgVar     Var(&Division) Value(%sst(*LDA  26 40))   

ChgVar     Var(&State)    Value(%sst(*LDA 234  2))   

ChgVar     Var(&Company)  Value(%sst(*LDA 236  3))   

                                                     

SndRcvF    RcdFmt(Prompt)                            

DoWhile    Cond(*not &IN03)                          

                                                     

           /* Various edit checks on user input */   

           /* If all is OK, then run the report */   

                                                     

           ChgVar Var(%sst(*LDA 234 2)) Value(&State)     

           ChgVar Var(%sst(*LDA 236 3)) Value(&Company)   

           ChgVar Var(%sst(*LDA 301 8)) Value(&FromDate)  

           ChgVar Var(%sst(*LDA 309 8)) Value(&ToDate)    

                                                          

           Select                                         

              When Cond(&Option = '1') Then( +            

                   Call Pgm(A))                           

              When Cond(&Option = '2') Then( +            

                   SbmJob Cmd(Call Pgm(B)))               

              When Cond(&Option = '3') Then(Do)           

                   Call Pgm(C)                             

                   Call Pgm(D)                            

                   EndDo                                  

           EndSelect                                      

           SndRcvF RcdFmt(Prompt)                          

EndDo                                                     

EndPgm       

 

The program, after declaring the LDA_DSPF display file, accesses five fields from the LDA—device name, user name, the name of the division the report is being run for, the state most recently used by the user, and the company within the division that the report is for—and loads these values into the variables used by the display file. Other fields available in the LDA—for instance, the current year and most recent invoice number—are not used. The program then prompts the user for how the report should be run, validates that the values entered meet certain criteria (not shown), stores the selections in the LDA, and then either calls or submits to batch the appropriate report-writing program.

 

A rather straightforward program, but it would be easy to also introduce mistakes when first writing (or later maintaining) this program. The use of substring start positions (such as 236 for the company ID) and substring lengths (3 bytes, starting at position 236, for the company ID) with each CHGVAR command provides one obvious place where errors could be made. The risk of these types of mistakes can, of course, be mitigated by copying previous tested CHGVAR commands from another program (rather than actually typing in the start and length values). I often find, though, that program variable names can differ quite a bit. For instance LDA_TRAD uses the variable &Company to hold the contents of positions 236 through 238 of the LDA, but other programs may refer to this data as &CompCode, &CmpnyCode, or &CompanyNbr. This difference in naming is certainly nothing overwhelming to developers wanting to copy select CHGVAR commands, but it has the potential for slowing them down a bit. A developer, of course, also needs to locate these five specific CHGVARs within the various existing CL application programs that might be using these fields (along with LDA-based fields, such as Year, that aren't need by LDA_TRAD).

 

Rather than accessing the LDA as shown above, where start and length values are specified with the CHGVAR command, wouldn't it be more productive to just have one set of tested LDA definitions? Definitions with meaningful and consistent CL variable names associated with them? Needless to say, you can.

 

I have, in previous articles, discussed the use of *Defined storage in the context of working with structured data such as that found with many system APIs. Structured data can exist, though, in many areas of the system. The LDA, for our sample company and its application standards for LDA usage, can certainly be thought of as a form of structured data. If you have standards within your organization on how the LDA is used, you could, using the CL-defined storage capabilities introduced in V5R4, write and test one set of definitions that can be shared by your developers. Using the LDA definition previously shown for our sample application, you could for instance use *Defined storage to provide the following Declare CL Variable (DCL) definitions:

 

Dcl        Var(&LDA)        Type(*Char) Len(1024)       

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

             Stg(*Defined)  DefVar(&LDA 1)              

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

             Stg(*Defined)  DefVar(&LDA 11)             

  Dcl      Var(&LDA_DivNam) Type(*Char) Len(40) +       

             Stg(*Defined)  DefVar(&LDA 26)             

  Dcl      Var(&LDA_RepOrg) Type(*Char) Len(2) +        

             Stg(*Defined)  DefVar(&LDA 196)            

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

             Stg(*Defined)  DefVar(&LDA 230)            

  Dcl      Var(&LDA_State)  Type(*Char) Len(2) +        

             Stg(*Defined)  DefVar(&LDA 234)                 

  Dcl      Var(&LDA_Cmpny)  Type(*Char) Len(3) +             

             Stg(*Defined)  DefVar(&LDA 236)                 

  Dcl      Var(&LDA_Order)  Type(*Char) Len(6) +             

             Stg(*Defined)  DefVar(&LDA 239)                  

  Dcl      Var(&LDA_FrmDat) Type(*Char) Len(8) +             

             Stg(*Defined)  DefVar(&LDA 301)                 

  Dcl      Var(&LDA_ToDat)  Type(*Char) Len(8) +             

             Stg(*Defined)  DefVar(&LDA 309)                  

 

Here, we define the CL variable &LDA to represent the entire 1024 bytes of the LDA. You could of course define a smaller &LDA if your company is using only the first n bytes of the LDA. Then, using defined storage, subfields of &LDA are declared. For instance, the CL variable &LDA_Cmpny is defined as the three bytes of &LDA starting at position 236. This in turn enables the developer to set the display file field &Company with the following Change Variable command:

 

ChgVar     Var(&Company)  Value(&LDA_Cmpny)                  

 

And, prior to calling or submitting the report-writing program, change the appropriate LDA value to the user-selected company with a similar command:

 

ChgVar     Var(&LDA_Cmpny)  Value(&Company)

 

Not exactly earth shattering, but certainly easier to understand (and write) than the equivalent

 

ChgVar     Var(&Company)  Value(%sst(*LDA 236  3))

      

and

 

ChgVar     Var(%sst(*LDA 236 3)) Value(&Company)

 

Assuming that you have stored the previous &LDA-related declares in a source member named LDA_CP, you could then utilize them in the new program LDA_NEW as shown below.

 

Pgm                                     

                                        

Include    SrcMbr(LDA_CP)         

                                         

DclF       File(LDA_DSPF)                                  

                                                           

RtvDtaAra  DtaAra(*LDA)   RtnVar(&LDA)                     

ChgVar     Var(&Device)   Value(&LDA_DevNam)                

ChgVar     Var(&User)     Value(&LDA_UsrNam)               

ChgVar     Var(&Division) Value(&LDA_DivNam)               

ChgVar     Var(&State)    Value(&LDA_State)                

ChgVar     Var(&Company)  Value(&LDA_Cmpny)                

                                                            

SndRcvF    RcdFmt(Prompt)                           

DoWhile    (*not &IN03)                             

                                                    

           /* Various edit checks on user input */  

           /* If all is OK, then run the report */  

                                                    

           ChgVar Var(&LDA_State)  Value(&State)    

           ChgVar Var(&LDA_Cmpny)  Value(&Company)  

           ChgVar Var(&LDA_FrmDat) Value(&FromDate) 

           ChgVar Var(&LDA_ToDat)  Value(&ToDate)   

           ChgDtaAra DtaAra(*LDA)  Value(&LDA)  

                                                    

           Select                                   

              When Cond(&Option = '1') Then( +      

                   Call Pgm(A))                     

              When Cond(&Option = '2') Then( +      

                   SbmJob Cmd(Call Pgm(B)))         

              When Cond(&Option = '3') Then(Do)     

                   Call Pgm(C)                     

                   Call Pgm(D)                     

                   EndDo                           

           EndSelect                               

           SndRcvF RcdFmt(Prompt)                   

EndDo                                              

                                                   

EndPgm       

 

These are the changes in LDA_NEW, relative to LDA_TRAD:

 

  • Use of the Include (INCLUDE) command to imbed the LDA_CP source member at compile time. Note that this command became available with V6R1, so if you are on V5R4, you will need to copy the source of LDA_CP into your source program using your editor of choice.

 

  • Use of the Retrieve Data Area (RTVDTAARA) command to retrieve the current contents of the LDA to variable &LDA. Note that you could also use the CHGVAR command to retrieve the LDA values to &LDA; it's your choice.

 

  • Changing the various CHGVAR commands from LDA substring references to simple CL variable name references.

 

  • Use of the Change Data Area (CHGDTAARA) command to update the LDA prior to calling or submitting the appropriate report-writing application program. As with the previous RTVDTAARA usage, you could elect to update the LDA using a command such as

 

      ChgVar Var(%sst(*LDA 1 1024)) Value(&LDA)

 

In return for these changes, you end up with more consistent application programs and program source that is easier to write, debug, maintain, and review.

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.

as/400, os/400, iseries, system i, i5/os, ibm i, power systems, 6.1, 7.1, V7,

                                                    

Bruce Vining

Bruce Vining is president and co-founder of Bruce Vining Services, LLC, a firm providing contract programming and consulting services to the System i community. He began his career in 1979 as an IBM Systems Engineer in St. Louis, Missouri, and then transferred to Rochester, Minnesota, in 1985, where he continues to reside. From 1992 until leaving IBM in 2007, Bruce was a member of the System Design Control Group responsible for OS/400 and i5/OS areas such as System APIs, Globalization, and Software Serviceability. He is also the designer of Control Language for Files (CLF).A frequent speaker and writer, Bruce can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it.. 


MC Press books written by Bruce Vining available now on the MC Press Bookstore.

IBM System i APIs at Work IBM System i APIs at Work
Leverage the power of APIs with this definitive resource.
List Price $89.95

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: