04
Mon, Nov
1 New Articles

ILE Tutorial: How to Use Embedded Sub-Procedures Within a Program

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

Say goodbye to old RPG subroutines, and get to know ILE RPG's powerful sub-procedures

Editor's Note: This article is excerpted from chapter 7 of 21st Century RPG: /Free, ILE, and MVC, by David Shirey.

The idea behind a sub-procedure is simple: take some code lines that are doing a particular task, take them out of the mainline code, and put them in a little spot of their own. Very similar to subroutines. But there are some major differences.

First, sub-procedures can only be done in an ILE program. They cannot be done in OPM.

Second, sub-procedures are not delineated by the BEGSR/ENDSR tags, but by B and E (beginning and end) P-specs. More on P-specs in a minute or so (depending on how fast you read).

Third, and this is a big one, sub-procedures allow you to define local variables in between the B and E P-specs.

You do this using D-specs that are listed after the B P-spec. This way, you can define any variable you want and use it in the sub-procedure. But only in the sub-procedure. Local variables cannot be used in any other part of the program. They are strictly for the sub-procedure. In fact, you could even give them the names of global variables that are used other places in the program or repeat the names of local variables from other sub-procedures. I don't recommend either of those options, but it's doable.

I can't tell you how important I think local variables are and how dangerous global variables are to good program structure.

Fourth, while subroutines are accessed by using the EXSR operator, sub-procedures are "called" by doing a prototype call (CALLP). Even within a given program.

You might think there is more work involved in doing a call rather than just an EXSR, but the truth is - well, actually, I guess the truth is it is a bit more work. But only a bit. And it's well worth it to have the other advantages.

And fifth, while subroutine code must exist in the program that is using it, a sub-procedure can actually be set up in a separate program (a service program) that is truly called into the calling program using the CALLP prototype call. Service programs are an incredibly useful entity, and we will talk more about them in a couple of chapters.

Sub-Procedure Inside a Program Example

Let's start our ILE adventures by looking at a program that calls an embedded sub-procedure (that is, the sub-procedure is part of the program that uses it). The sub-procedure itself is very simple; it just validates a product number against a product master (MSPMP100). We will look at the whole mess, then break it down into its components for easy digestion. Give it a name to your own liking.

H********************************************************

H DFTACTGRP(*NO) ACTGRP(*NEW)

H********************************************************

F* PRODUCT MASTER

FMSPMP100 IF   E           K DISK   PREFIX(PM_)

F*

F* Display File

FDWS0170FM CF   E             WORKSTN PREFIX(D01_)

F********************************************************

D VAL_PRDNO     PR

D   D01_PRDNO                 15

D   MSG                       60

D   ERROR_FLAG                 1

D*

D ERROR_FLAG     S             1

D MSG           S             60

D********************************************************

/FREE

  

     ERROR_FLAG = 'N';

 

     CALLP VAL_PRDNO(D01_PRDNO:MSG:ERROR_FLAG);

 

     *INLR = '1';  

 

/END-FREE

    

P********************************************************

P // SUBPROCEDURE - VALIDATE PRODUCT# FROM PRODUCT MSTR

P VAL_PRDNO     B

D********************************************************

D VAL_PRDNO      PI

D   D01_PRDNO                 15

D   MSG                       60

D   ERROR_FLAG                 1

D*

D SP_PRDNO       S             15

D********************************************************

/FREE

//READ PRODUCT MASTER USING PRODUCT NUMBER FROM SCREEN

//AS KEY.

   EVAL SP_PRDNO = D01_PRDNO;

   CHAIN (SP_PRDNO) MSPMP100;

   IF NOT %FOUND;

       ERROR_FLAG = 'Y';

       MSG = 'THIS IS A BAD PRODUCT NUMBER

                                 (XXX00111.01).';

   ENDIF;

/END-FREE

P VAL_PRDNO     E

P*******************************************************

Now let's take that program apart and see what makes it tick. You should be able to detect hints of apricot and chocolate and ... but there I go again. Each person tastes something different, and I shouldn't try to plant suggestions.

Because I am doing this as if you are on 5.4 rather than 7.x, some things are present that may not be if you are on a more recent release of the software. Like having the F-, D-, and other specs be positional, and then having to use /Free and /End-Free to segregate the /Free from the positional code. Or the need for the H-spec to ensure this is compiled as ILE (more on that later). Sorry about that, but many of us are still back in that old era. It should not stop you from doing ILE.

Oh, and by the way, I am listing the code first, and then under it putting the discussion of that code. I would have been confused about that myself. As you go thru this section, DON'T focus on the text description. Focus on the code, devour it with your eyes, think about what you see, experience its richness and vibrancy. The text description is just to give it context, to help clarify what you are seeing. But focus on the code itself.

H********************************************************

H DFTACTGRP(*NO) ACTGRP(*NEW)

H********************************************************

First, the H-spec. This is put in there because sub-procedures are an ILE construct. So they cannot be in a program that uses the default activation group (that is OPM). The H-spec makes sure that the program is compiled as ILE, but if the defaults in your compile command are set for that, then you would not need this H-spec. I am assuming you will compile this with CRTBNDRPG instead of CRTRPGMOD/CRTPGM.

F*

F* PRODUCT MASTER

FMSPMP100 IF   E         K DISK   PREFIX(PM_)

F*

F* Display File

FDWS0170FM CF   E           WORKSTN PREFIX(D01_)

F*******************************************************

This is then followed by the F-specs for this program.

Note that I am using a product master file plus a display file, and I am going to be pretending that I am picking up data entry fields from the display and editing them against the product master file for validity.

Remember, if you are on 7.1, TR7 or higher, we could set these up as file control statements. But since I am doing this book from a 5.4 perspective, we will set them up as F-specs.

D*

D VAL_PRDNO       PR

D   D01_PRDNO                 15

D  MSG                       60

D   ERROR_FLAG                 1

D

D ERROR_FLAG     S             1

D MSG             S           60

D********************************************************

Then come the D-specs. The global D-specs. We are still in our mainline program here; we haven't gotten to the sub-procedure yet. Just be patient, and quiet ... very, very quiet. We don't want to spook it.

There are two things here in the D-specs. The first is the prototype D-spec, the thing identified with the PR as the D-spec data type. This is required in the program D-specs, and it identifies what sub-procedures will be used (by the CALLP) in that program. The D-spec subfields under it for D01_PRDNO, MSG, and ERROR_FLAG are the data elements that are passed in when the sub-procedure is "called." Please note that there is no EXTPGM keyword on the PR, because we are not calling an external program, just a sub-procedure in this program.

If you had more than one sub-procedure embedded in this program, then you would need a PR prototype D-spec for each one of those sub-procedures.

Below that are two more D-specs: ERROR_FLAG and MSG.

ERROR_FLAG is a global data element, and it is used in the sub-procedure but also in the program calling the sub-procedure. Our little snippet does not show the ERROR_FLAG being used, but if there were more calls to other sub-procedures, they would be contained within an IF statement checking to see whether or not the ERROR_FLAG were set.

MSG is also a global variable, just a message field that we will set if there is an error.

What is interesting is that both of these fields are defined under the PR D-spec. So why are we defining them here again? Have I screwed up, defined them twice, and so the compile will fail? Normally, that would be a very good guess indeed, but not tonight. They are there because even though I have "defined" them in the PR above, anything listed in a PR is not really defined. It has to exist somewhere else, and so I have defined the field in a second, normal D-spec. Why aren't things in a PR really defined to the system as fields? You might as well ask why the earth is an oblate spheroid. Because. Just because that's the way it is. Deal with it.

/FREE

 

     ERROR_FLAG = 'N';

 

     CALLP VAL_PRDNO(D01_PRDNO:MSG:ERROR_FLAG);

 

     *INLR = '1';

 

/END-FREE

This is the /Free code that calls the sub-procedure.

And it's very simple. I set the ERROR_FLAG (a global variable) to 'N', then call the sub-procedure, and then end the program. If this were a real program, we would probably have more calls to other sub-procedures, each covered by an IF ERROR_FLAG clause, to edit each of the fields on the display file. Oh, I guess I did use the ERROR_FLAG, after all, to initialize it.

Note that the call to the sub-procedure VAL_PRDNO is actually a call, using CALLP (Call Prototype).

And notice that the three data fields mentioned (can't really say defined) in the VAL_PRDNO PR are sent to the sub-procedure as parms separated by a colon and surrounded by parentheses.

Just as an interesting side note, if there were no parms being sent to the sub-procedure, then nothing would be listed under the PR line in the D-specs (although we would still need the PR itself), and nothing would be included in the parenthesis on the CALLP. However, the parenthesis would still be included; they would just be empty - ().

Finally, the /end-Free delimiter needs to be set because when we define the sub-procedure (next step), we will use P-specs and D-specs, which are positional RPG, not /Free. Granted, in 7.1 TR7, we can make them /Free, but that is not the version of the operating system that this book is based on.

P**********************************************************  

// SUBPROCEDURE - VALIDATE PRODUCT # FROM PRODUCT MSTR.

P VAL_PRDNO       B

D**********************************************************

D VAL_PRDNO     PI

D   D01_PRDNO                 15

D   MSG                       60

D   ERROR_FLAG                 1

D*

D SP_PRDNO       S             15

D**********************************************************

The sub-procedure itself really starts with the P-spec that has a B in position 24. The two lines above that are just icing that I put in to make it easier to see. Note that even though I have come out of /Free (last statement on previous page), I can still use the double slash for comments. Pretty cool, eh?

Then we have D-specs for the sub-procedure. If you are on a release 6.1 or above, you can also include F-specs in here, so instead of defining the files at the global level, you can define them in the sub-procedure. (This is separate from the stuff in 7.1 TR7.) But we are at 5.4, so that option is not open to us.

Note that we have another D-spec that defines the prototype, but this one is a PI, which is called the procedure interface. So, we have a PR in the program and a PI in the sub-procedure. Let's replay that one more time. The PR is the prototype D-spec; the PI is the procedure interface D-spec. Try to remember that.

Then, we have one more D-spec for SP_PRDNO. Technically, this field is not necessary for the functioning of this module. I could have just as easily used the global variable D01_PRDNO from the display file, but I was so excited about local variables that I just had to define one. If you tried to use this local variable (SP_PRDNO) in the mainline code above, you would get a compile error saying the data element was undefined. But you can use it in the sub-procedure code below.

Please note that the PR and PI specs are D-specs. D-specs. The P-specs are just used to denote the start and finish of the sub-procedure as a whole.

/FREE

   //READ PRODUCT MASTER USING PRODUCT # FROM SCREEN.

       EVAL SP_PRDNO = D01_PRDNO;

       CHAIN(E) (SP_PRDNO) MSPMP100;

       IF NOT %FOUND;

           ERROR_FLAG = 'Y';

           MSG = 'THIS IS A BAD PRODUCT NUMBER +

                                 (XXX00111.01).';

       ENDIF;

/END-FREE

P VAL_PRDNO       E

P*********************************************************

Finally, we are into the code for the sub-procedure. As you can see, we are going back to /Free here, and the code is very simple. Like subroutines, all the sub-procedures will be listed after the *INLR = '1' in the mainline logic.

Even though I don't need it, I set the local variable equal to the value from the display file and used that to read the product master file. I could have just as easily used D01_PRDNO, which is a global variable, in the statement. There is no advantage to using the local variable here; I just wanted to showcase it. There are, however, advantages in general to using local variables.

If it doesn't get a hit, I set the ERROR_FLAG to 'Y' and throw message verbiage into the MSG field. Both of these values (the parms) are returned and can be used in the mainline code. The only thing that can't be used in the mainline is the local variable SP_PRDNO.

Finally, the very last line in the whole mess is another P-spec, this one with a E (for End). If there were other sub-procedures in the program, they would be listed below just as we list subroutines below each other at the very end of the program.

David Shirey

David Shirey is president of Shirey Consulting Services, providing technical and business consulting services for the IBM i world. Among the services provided are IBM i technical support, including application design and programming services, ERP installation and support, and EDI setup and maintenance. With experience in a wide range of industries (food and beverage to electronics to hard manufacturing to drugs--the legal kind--to medical devices to fulfillment houses) and a wide range of business sizes served (from very large, like Fresh Express, to much smaller, like Labconco), SCS has the knowledge and experience to assist with your technical or business issues. You may contact Dave by email at This email address is being protected from spambots. You need JavaScript enabled to view it. or by phone at (616) 304-2466.


MC Press books written by David Shirey available now on the MC Press Bookstore.

21st Century RPG: /Free, ILE, and MVC 21st Century RPG: /Free, ILE, and MVC
Boost your productivity, modernize your applications, and upgrade your skills with these powerful coding methods.
List Price $69.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: