Here’s a self-assessment score card that will provide
insight into your knowledge of ILE RPG. Many of the skills listed here require
knowledge of newer or more advanced ILE RPG language features and are essential
to incorporating contemporary "best practices" into your development
work.
Each entry below asks you to rate your knowledge of a
particular ILE RPG feature.
This self-assessment isn’t intended as a comprehensive
test of essential RPG programming skills, such as declaring and using files.
Most RPG language features for core programming tasks, such as file I/O, have
been around a long time, many dating back even to RPG III on the S/38.
Essentially, the self-assessment here is meant to provide a measure of how well
you’re keeping up with more recent ILE RPG programming skills that can help you
write better-structured, more flexible, and more reliable programs.
For each of the ILE RPG features listed, rate your
knowledge using the following scale:
0 — Know very little
about why or how to use the feature
1 — Have some idea what
the feature does, but not sure how to use it
2 — Have enough basic
understanding to use the feature in limited ways
3 — Have a full
understanding of when and how to use the feature
When you’ve completed the inventory, you sum your
individual ratings to see how you stand.
Control
(H) Specifications
You can use H-specs to control a variety of important
compilation options. In many cases, an H-spec keyword is equivalent to a
parameter you can specify on the CrtBndRpg and CrtRpgMod commands.
Several H-spec keywords are covered in other sections of
the assessment. This section includes useful keywords that don’t fit neatly
elsewhere.
Rate your knowledge about the following H-spec
keywords, and give a brief summary of your understanding:
1.
ActGrp and DftActGrp 2
When an OS/400 job is started,
the system creates two activation groups to be used by all other OPM programs.
The default activation groups use single-level store for static program
variables. You cannot delete the OPM default activation groups. They are
deleted by the system when your job ends.
Note:
APIs cannot be used
if DFTACTGRP(*YES) is specified on the CRTBNDRPG CL command. ILE static binding
is not available when a program is created with DFTACTGRP(*YES). This means
that your program cannot contain a CALLB operation. DFTACTGRP(*YES) specified, the RCLRSC command frees
static storage.
The Reclaim Activation Group (RCLACTGRP) command can be used to delete a
nondefault activation group that is not in use.
2. NoMain 2
There is no PEP, and
therefore much of the tasks done at program start-up, including the loading of
the logic cycle, are not done. This lightens the object significantly. It also
means that in addition to the service program not being able to be called
directly, the modules can't be called, either. The only way to access the
service program is through the subprocedures. The module becomes little more
than a container for its subprocedures.
NOMAIN modules cannot be called directly. Instead, the subprocedures
contained inside the module are called using prototyped call (CALLP in RPG).
3. Optimize 3
Generally, if a module has creation data, you can change the level at
which the source code is optimized to run on the system. Processing shortcuts
are translated into machine code, allowing the procedures in the module to run
more efficiently.
The higher the optimization level, the more efficiently the procedures
in the module run. However, with more optimization you cannot change variables
and may not be able to view the actual value of a variable during debugging.
When you are debugging, set the optimization level to 10 (*NONE). This provides
the lowest level of performance for the procedures in the module but allows you
to accurately display and change variables. After you have completed your
debugging, set the optimization level to 30 (*FULL) or 40. This provides the
highest level of performance for the procedures in the module. The system looks
for processing shortcuts that reduce the amount of system resources necessary
to produce the same output. The higher the optimization level, the more
efficiently the procedures in the module run.
4. Option( *NoExpDds ) 3
Do not show the expansion of externally described files in the listing
or display key field information.
5. UsrPrf 3
USRPRF
Specifies the user profile that will run the created program object. The
profile of the program owner or the program user is used to run the program and
to control which objects can be used by the program (including the authority
the program has for each object). This parameter is not updated if the program already
exists. To change its value, you must delete the program and recompile using
the new value (or, if the constituent *MODULE objects exist, you may choose to
invoke the CRTPGM command).
*USER
The program runs under the user profile
of the program’s user.
*OWNER
The program runs under the user profile of both the program’s user and owner.
The collective set of object authority in both user profiles are used to find
and access objects while the program is running. Any objects created during the
program are owned by the program’s user.
File
(F) Specifications and Database Operations
Externally described files have been around since the
first S/38 shipped. They’re a core OS/400 feature that a competent RPG
programmer must master. But several features that have been around for a while
(e.g., user-controlled opens and transaction support) aren’t yet as widely used
as they should be. And a few newer features, such as specifying which library,
file, and or member should be opened, belong in every programmer’s arsenal.
Rate your knowledge about the following F-spec
keywords, and give a brief summary of your understanding:
6. Commit 3
Ensure one of two
outcomes for the file operations:
a)
All of the file operations are successful (a commit
operation)
b)
None of the file operations has any effect (a rollback
operation).
In this way, you
process a group of operations as a unit.
7. ExtFile and ExtMbr 3
Controls which external file/member is used when a file is
opened.
Specifies which file/member is opened.
The value can be a literal or a variable.
The default file name is the name specified in position 7 of the file specification.
The default library is *LIBL.
The default is
*FIRST for member
FACCLG01 UF A
E K DISK RENAME(FORMAT1:FORMAT_X)
FACCLG02 UF A
E K DISK RENAME(FORMAT1:FORMAT_Y)
V5R1
FFile1 if
e Disk Extfile(FilNam) ExtMbr(Member Name)
8. IndDs 3
Associate a data structure name with
the INDARA indicators for a workstation or printer file. This data structure
contains the conditioning and response indicators passed to and from data
management for the file, and is called an indicator data structure. By default,
the indicator data structure is initialized to all zeros (’0’s).
9. UsrOpn 3
The USROPN keyword
causes the file not to be opened at program initialization.
This gives the programmer control of the file’s first open. The file
must be explicitly opened using the OPEN operation in the calculation
specifications.
Rate your knowledge about the following D-spec
keywords, and give a brief summary of your understanding:
10. Using LikeDs(…: *Key)
and LikeRec(…: *Key) to declare a key data structure. 2
The LIKEDS keyword is used to define a data structure, prototyped return
value, or prototyped parameter like another data structure. The subfields of
the new item will be identical to the subfields of the other data structure. The
LIKEREC keyword is used to define a data structure subfield
like a record. The subfields of the data structure will be the same as the
fields in the record.
The *Key definition will indicate that the
Data structure can be used in a keyed specification example %KDS()
Rate your knowledge about the following database I/O
operation features, and give a brief summary of your understanding:
11. Open and Close
operations 3
Open file operations result in the creation of a temporary resource that
is called an open data path (ODP). You can start the open function by using
HLL open verbs, the Open Query File
(OPNQRYF) command, or the Open
Data Base File (OPNDBF) command. The ODP is scoped to the activation group
of the program that opened the file. For OPM or ILE programs that run in the
default activation group, the ODP is scoped to the call-level number. To change
the scoping of HLL open verbs, you can use an override. You can specify scoping
by using the open scope (OPNSCOPE) parameter on all override commands, the
OPNDBF command, and the OPNQRYF command.
The system automatically closes any files scoped to the activation group
when the activation group ends. This includes any database files scoped to the
activation group opened under commitment control. The close operation for any
such file occurs before any implicit commit operation that is performed for the
commitment definition at the activation-group level. Therefore, any records
that reside in an I/O buffer are first forced to the database before any
implicit commit operation is performed.
12. Using %KDS function
or free-form key list in a keyed I/O operation 2
Used
to do the search in a keyed defined data structure where *Key was defined.
Allowed as the search argument for any
keyed Input/Output operation (CHAIN, DELETE, READE, READPE, SETGT, SETLL) coded
in a free-form group.
A..........T.Name++++++RLen++TDpB......Functions++++++++++++++++++
A
R CUSTR
A
NAME 100A
A
ZIP 10A
A
ADDR 100A
A
K NAME
A
K ZIP
FFilename++IPEASF.....L.....A.Device+.Keywords+++++++++++++++++++
Fcustfile
if e k disk rename(CUSTR:custRec)
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++
D custRecKeys ds likerec(custRec : *key)
...
/free
// custRecKeys is a qualified data structure
custRecKeys.name = customer;
custRecKeys.zip = zipcode;
// the *KEY data structure is used as the search argument for CHAIN
chain %kds(custRecKeys) custRec;
/end-free
13. Using %Fields function
in an Update operation 2
Only the fields in the %Fields argument
list will be updated of the record.
/free
chain empno record;
salary = salary + 2000;
status = STATEXEMPT;
update record
%fields(salary:status);
/end-free
14. *Start and *End
special values for SetLL operation 2
The
*Start and *End keyword are used to set the reading pointer in a file. By using
the SETLL the *Start the pointer is set to read the first record and *End will
reach end of file. By using *End one can use the read prior opcode to read the
last record.
SETLL
*Start Recid;
SETLL
*End Recid;
Rate your knowledge about the following transaction
support features, and give a brief summary of your understanding:
15. Commit and Rollbk
operations 3
The COMMIT operation tells the system that you have completed a group of
changes to the files under commitment control. The ROLBK operation eliminates the
current group of changes to the files under commitment control.
Definition
(D) Specifications: General Features
If you’re still programming with D-specs as they
existed several years ago, it’s time to crack the books and get familiar with
newer features.
This section focuses on features common to different
kinds of variable declarations. The Procedure
Definition section covers parameter declarations.
Several other sections include additional D-spec features, as well.
Rate your knowledge about declaring and using the
following types of variables, and give a brief summary of your understanding:
16. Variables with long
names (i.e., greater than fourteen characters) 2
DMyVaryLongVariableName1234568...
D s 10 A
The field
name has to have 3 dots behind it to indicate the definition will overflow onto
the next line.
17. Mnemonics (named
constants) 3
A constant field is
defined with type “C” and is assigned a value within the definition
DConstantVariable c 'abcdef'
18. Variable-length character variables 3
The variable in memory,
will vary during runtime. So when using the variable, the program must state
the max length or size of the variable. Used where some character value might
be short, long, or not used all the time to save system resources.
DMyVarCharVariable 100 A (*varsize)
19. Boolean (indicator)
variables 3
Indicators has a two-character name (for example, LR, 01, H3), and is referred
to in some entries of some specifications just by the two-character name and in
others by the special name *INxx where xx is the two-character nam and can contain only 0 or 1, true or false.
20. Data structures with
qualified subfield names 3
Qualified data structure names allow you to refer to the
subfields (Field1/2) of a data structure by qualifying them to the data
structure name itself (struct).
Dstruct
DS
D Field1 20 A
D Field2 20 A
Rate your knowledge about the following D-spec
keywords, and give a brief summary of your understanding:
21. Like 3
Used as a keyword to
define a variable to have the same attributes as the field specified in the
keyword. D CustIdNum s 20 A
D
CustIdNum2
Like( CustIdNum)
Used for standalone fields, prototypes, parameters and
data-structure subfields.
22. LikeDs and LikeRec 3
Same as point 10, but no *KEY instruction
specified.
23. NoOpt 2
Prevent optimization of data
items that you do not want to optimize.
24. Overlay 3
Used in data structures
to overlay DS fields in a specific memory space. Example
D
Structure DS
D MyDStruct 10A
D Field1 3A OVERLAY(MyDStruct)
D Field2 6A OVERLAY(MyDStruct:4)
D Field3 1A OVERLAY(MyDStruct:10)
*
Define subfield overlay positions with *NEXT
D
Structure DS
D MyDStruct 10A
D Field1 3A OVERLAY(MyDStruct)
D Field2 6A OVERLAY(MyDStruct:*NEXT)
D Field3 1A OVERLAY(MyDStruct:*NEXT)
25. Prefix 3
You can partially rename all fields in an externally described file,
either add a prefix to the existing field name or you can replace part of the
existing field name with a sequence of characters
FITMMSTL IP E K DISK
PREFIX(MST)
FSALESMSTR IP E K DISK
PREFIX(YE:3)
The format is
PREFIX(prefix-string:{nbr_of_char_replaced}).
Runtime
Feedback and Error Handling
A programmer must have familiarity with ILE RPG’s
facilities for obtaining runtime feedback, including detection and handling of
runtime errors. A mix of old and new features provides the foundation for this
aspect of professional RPG programming.
Rate your knowledge about the following runtime
feedback structures, and give a brief summary of your understanding:
26. File Information Data
Structure 3
A file information data structure (INFDS) can be defined for each file
to make file exception/error and file feedback information available to the
program. The file information data structure, which must be unique for each
file, must be defined in the main source section. The same INFDS is used by all
procedures using the files.
FMYFILE IF E DISK INFDS(FILEFBK)
DFILEFBK DS
D FILE *FILE * File name
D OPEN_IND 9 9N * File open?
D EOF_IND 10 10N *
File at eof?
D STATUS *STATUS * Status
code
D OPCODE *OPCODE * Last opcode
D ROUTINE *ROUTINE * RPG Routine
D LIST_NUM 30 37 *
Listing line
D SPCL_STAT 38 42S 0 * SPECIAL
status
D RECORD *RECORD * Record
name
D MSGID 46 52 * Error MSGID
D SCREEN *SIZE * Screen size
D NLS_IN *INP * NLS Input?
D NLS_OUT *OUT * NLS Output?
D NLS_MODE *MODE * NLS Mode?.
27. Program Status Data
Structure 2
A program status data structure (PSDS) can be defined to make program exception/error
information available to an RPG IV program. The PSDS must be defined in the
main source section; therefore, there is only one PSDS per module.
D Psds SDS
D Loc *ROUTINE
D Err *STATUS
D Parms *PARMS
D Name *PROC
.
Rate your knowledge about the following error
detection and handling features, and give a brief summary of your
understanding:
28.
(E) opcode extender 2
Handling
Exceptions ILE RPG supports the following types of exception
handlers:
a)
RPG-specific handlers, for example, the use of an
error indicator, an ’E’ operation code extender, a MONITOR group, or a *PSSR or
INFSR error subroutine.
b)
ILE condition handlers, user-written exception
handlers that you register at run time using the ILE condition handler bindable
API CEEHDLR.
c) ILE cancel handler which can be used when a procedure
ends abnormally.
C
CustNO Chain(E) CustMast
C
if %ERROR = *ON C
Select
C
When %STATUS = 1221
C
exsr UpdateNoRead
C
When %STATUS = 1218
C
exsr RecdLocked
C
endSL
C
ELSE
C
if
%FOUND( CustMast )
C
exsr check
C
endif
C
endif
29. *PSSR subroutine 2
Code a program error subroutine, which is named *PSSR, for program
exceptions. Note that a *PSSR is local to the procedure in which it is coded.
This means that a *PSSR in a main procedure will handle only those
program errors associated with the main procedure. Similarly, a *PSSR in a
subprocedure will only handle the errors in that subprocedure.
Fmyfile IF
E K DISK INFSR(*PSSR)
CSR
*PSSR begsr
C eval MsgID = CPFID
C eval MsgTyp = '*INFO'
C eval MsgDta = CPFMsg
C eval CMsgQ = '*EXT'
C eval CStack = 0
C exsr Sndmsg
C eval *InLR = *on
C return
CSR endsr
30. Monitor blocks 2
MONITOR group
performs conditional error handling based on the status code.
If an error occurs, control passes to
the appropriate ON-ERROR group within the
MONITOR group.
C MONITOR
C READ FILE1
C IFNOT %EOF
C EVAL Line = %SUBST(Line(i) :
C %SCAN('***': Line(i)) + 1)
C ENDIF
C ON-ERROR 1211
C ... handle file-not-open
C ON-ERROR *FILE
C ... handle other file errors
C ON-ERROR 00100 : 00121
C ... handle string error and
array-index error
C ON-ERROR
C ... handle all other errors
C ENDMON
Rate your knowledge about the following error and I/O
status built-in functions, and give a brief summary of your understanding:
31. %Eof 3
%EOF returns ’1’ if the most recent read operation or write ended in an end of file or beginning of file condition; otherwise, it returns ’0’.
C READ ACCOUNT
C IF %EOF(ACCOUNT)
C 'EOF' DSPLY
C ENDIF
C IF NOT %EOF(ACCOUNT)
C IF %EOF
C EVAL *IN45=%EOF(ACCOUNT)
.
Please see point 30.
32. %Equal 3
%EQUAL returns ’1’ if the most recent relevant operation found an exact
match; otherwise, it returns ’0’.
C SearchName LOOKUP
TabNames
10 10
C SELECT
C WHEN %EQUAL
*
An exact match was found
C 'Exact 'DSPLY TabNames
C WHEN %FOUND
*
A name was found greater than SearchName
C 'Next greater'DSPLY TabNames
C OTHER
*
Not found. SearchName is greater than
all the names in the table
C 'Not found 'DSPLY SearchName
C ENDSL
C RETURN
33. %Error 3
Returns ’1’ if the most recent operation with extender ’E’ specified
resulted in an error condition. This is the same as the error indicator being
set on for the operation. Before an operation with extender ’E’ specified
begins, %ERROR is set to return ’0’ and remains unchanged following the
operation if no error occurs. All operations that allow an error indicator can
also set the %ERROR built-in function. The CALLP operation can also set %ERROR.
Please see point 28
34. %Found 3
Returns ’1’ if the most recent relevant file operation found a record, a
string operation found a match, or a search operation found an element.
Otherwise, this
function returns ’0’.
Please
see points 28 &32
35. %Open 3
Returns ’1’ if the specified file is open. A file is considered ″open″ if it has been
opened by the RPG program during initialization or by an OPEN operation, and
has not subsequently been closed. If the file is conditioned by an external
indicator and the external indicator was off at program initialization, the
file is considered closed, and %OPEN returns ’0’.
c
If Not %Open(FILE1)
c Open FILE1
c Endif
36. %Status 2
Returns the most
recent value set for the program or file status.
%STATUS is set whenever the program status or any file status changes,
usually when an error occurs.
Please see point 28
Extended
and Free-Format Syntax:
It’s now possible to write almost every bit of
executable code using a more readable and flexible free-format syntax. Okay, so
your nice-looking program might still be broken up by the notoriously clunky P-
and D-specs to define subprocedures. Still, it’s way past time to master and
use free format wherever you can.
Rate your knowledge about free-format syntax and
features, and give a brief summary of your understanding:
37. Coding arithmetic and
string expressions. 3
Expressions are a way to express program logic using free-form syntax.
They can be used to write program statements in a more readable or concise
manner than fixed-form statements.
An expression is simply a group of operands and operations. For example,
the following are valid expressions:
A+B*21
STRINGA + STRINGB
D = %ELEM(ARRAYNAME)
*IN01 OR (BALANCE > LIMIT)
SUM + TOTAL(ARRAY:%ELEM(ARRAY))
'The tax rate is ' + %editc(tax : 'A') +
'%.'
Functions for converting a number into a duration that can be used in
arithmetic expressions: %MSECONDS, %SECONDS, %MINUTES, %HOURS, %DAYS, %MONTHS,
and YEARS
38. (E) and (M) operation
extenders 2
(E) Please see point 28
(M) Default precision rule, the precision of a decimal intermediate in
an expression is computed to minimize the possibility of numeric overflow.
However, if the expression involves several operations on large decimal
numbers, the intermediates may end up with zero decimal positions. (Especially,
if the expression has two or more nested divisions.) This may not be what the
programmer expects, especially in an assignment.
39. Coding assignments
without an explicit Eval opcode. 3
The equal sign can be
used instead (makes for easier reading of code).
Y = A
+ B + C
However
EVAL must be used in a case where the result field name is the same as an
operational code
EVAL READ = A
+ B + C
40. Using free-format
syntax and Boolean expressions for control operations (e.g., If and For
opcodes). 2
D
pKxIndicators S * Inz(%Addr(*In))
D
FunctionKeys DS Based(pKxIndicators)
D thisIsKC N Overlay(FunctionKeys: 3)
D thisISKL N Overlay(FunctionKeys: 12)
/free
If thisIsKC and Not thisIsKL;
do_something();
EndIf;
enddo;
/end-free
/free
// Load a
subfile with the next 10 data records
For I = 1 to 10;
Read data_file; // Get next record
or eof
If %eof(data_file); // If eof
Leave; // Jump out of For loop
Endif;
// Load
subfile from data record here
Endfor;
// Leave
instruction sends control here
/end-free
41. Using free-format
version of opcodes for I/O and other operations. 3
/free
Setll
(Key1: Key2) MyFile;
Reade
(Key1: Key2) MyFile;
Dow
Not %Eof(MyFile) and %Found(MyFile);
Reade
(Key1: Key2) MyFile;
EndDo
/end-free
Rate your knowledge about these equivalent built-in
functions for fixed-format opcode capabilities, and give a brief summary of
your understanding:
42. %BitAnd, %BitOr,
%BitNot 1
* This example shows how to duplicate the function of * BITON and BITOFF using %BITAND, %BITNOT, and %BITOR
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++
D fld1 s 1a inz(x'01')
D fld2 s 1a inz(x'FF') CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++ C biton x'F4' fld1
* fld1 has an initial value of x'01' (0000 0001)
* The 1 bits in x'F4' (1111 0100) are set on
* fld1 has a final value of x'F5' (1111 0101)
C bitoff x'F1' fld2
* fld2 has an initial value of x'FF' (1111 1111)
* The 1 bits in x'F1' (1111 0001) are set off
* fld2 has a final value of x'0E' (0000 1110)
/free
43. %Char and other data
conversion functions 3
Convert the value of the expression from graphic, UCS-2, numeric, date,
time or timestamp data to type character. The converted value remains
unchanged, but is returned in a format that is compatible with character data.
D Name S 20G VARYING INZ(G'oXXYYZZi')
D date S D INZ(D'1997/02/03')
D time S T INZ(T'12:23:34')
D result S 100A VARYING
D points S 10i 0 INZ(234)
/FREE
result = 'It is ' + %CHAR(time) + ' on ' +
%CHAR(date);
result = 'It is ' + %CHAR(time : *jobrun)
+ ' on ' + %CHAR(date : *jobrun);
result = 'It is ' + %CHAR(time : *hms:)
+ ' on ' + %CHAR(date : *iso);
result = 'The time is now ' + %SUBST
(%CHAR(time):1:5) + '.';
result = 'The customer''s name is ' +
%CHAR(Name) + '.';
result = 'You have ' + %char(points) + '
points.';
/END-FREE
44. %Check and %CheckR 3
%CHECK returns the first position of the string base that contains a
character that does not appear in string comparator. If all of the characters in base also appear in comparator, the function
returns 0.
Dstring S 20 A inz('ZXCV123GHJGHJ')
/Free
If %Check('123': String) > 0;
//do something
EndiF
/End-Free
%CHECKR returns the last position of the string base that contains a
character that does not appear in string comparator. If all of the characters in base also appear in comparator, the function
returns 0.
. /Free
If %CheckR'123': String) > 0;
//do something
EndiF
/End-Free
45. %Date, %Time, and
%Timestamp 3
Functions for converting a character string (or date or timestamp) into
a date, time, or timestamp.
Useful in retrieving current system values, year/date/time calculations
facilitating different edit formats.
46. %Diff, %Years, and
%Months 3
%DIFF produces the
difference (duration) between two date or time values.
%YEARS converts a number into a duration that can be added to a date or
timestamp value. %MONTHS converts a number into a duration that can be added to
a date or timestamp value.
47. %Div and %Rem 3
%DIV returns the integer portion of the quotient that results from
dividing operands n by m. %REM returns the remainder that results from
dividing operands n by m.
48. %EditC and %EditW 3
%EDITC returns a
character result representing the numeric value edited according to the edit
code. In general, the rules for the numeric value and edit code are identical
to those for editing numeric values in output specifications.
%EDITW
returns a
character result representing the numeric value edited according to the edit
word. The rules for the numeric value and edit word are identical to those for
editing numeric values in output specifications.
49. %Lookup and %Tlookup
(including binary search feature) 3
Functions for
finding an element in an array: %LOOKUP, %LOOKUPGT,
%LOOKUPGE,
%LOOKUPLT, and %LOOKUPLE.
Functions for finding an element in a
table: %TLOOKUP, %TLOOKUPGT,
%TLOOKUPGE,
%TLOOKUPLT, and %TLOOKUPLE.
50. %Occur 2
Gets or sets the current position of a
multiple-occurrence data structure.
51. %Scan 3
%SCAN returns the first position of the search argument in the source
string, or 0 if it was not found. If the start position is specified, the
search begins at the starting position. The result is always the position in
the source string even if the starting position is specified. The starting
position defaults to 1.
52. %SubArr 2
Returns
a section of the specified array starting at start-index. The number of
elements returned is specified by the optional number-of-elements
parameter. If not specified, the number-of-elements defaults to the
remainder of the array.
53. %ShtDn 3
Allows the
programmer to determine whether the system operator has requested shutdown.
54. %SubDt 3
Extracts a portion
of the information in a date, time, or timestamp value. It returns an unsigned
numeric value.
55. %SubSt 3
Returns a portion of argument string. It may also be used as the result
of an assignment with the EVAL operation code.
56. %Xlate 3
Translates string according to the
values of from, to, and startpos.
57. %Xfoot 3
Results in the sum
of all elements of the specified numeric array expression.
Array
Declaration and Processing Features
Arrays are ubiquitous in application programs, and ILE
RPG’s support has been significantly improved in recent releases. If you still
think "array" means "multiple-occurrence data structure,"
it’s time to discover what you can now do with the real thing.
Rate your knowledge about the following D-spec
features, and give a brief summary of your understanding:
58. Declaring
two-dimensional arrays 1
D
Address
DS
DIM(20) QUALIFIED
D Street 30a
D City
20a
D
State
2a
D
Zip
5a
D
ZipPlus
4a
D
PrintAddr
DS
LikeDS(Address)
D
CurLine
S 2
0
C
If
Address(CurLine).City =
C
Address(CurLine - 1).City
C
Eval PrintAddr.City
= *Blanks
C
EndIf
59. Declaring arrays
whose elements are data structures 3
D Struct DS
D
Elemt1
10 A
D
Elemt2
3p 0
D
Elemt3
5 A
D MyArray S Dim(100) Like (Struct)
/Free
Elemt1 = '1234';
Elemt2 = 123;
Elemt3 = 'TEXT';
MyArray(1) = Struct;
/End-Free
60. Using the Inz and
Overlay keywords to specify initial values for an array. 3
D DS1
DS OCCURS(3)
D
Fld1
5A INZ(’ABCDE’)
D
Fld1a
1A DIM(5) OVERLAY(Fld1)
D
Fld2 5B 2
INZ(123.45)
Rate your knowledge about the following function and
feature: 3
61. %Elem
Returns the number of elements in the specified array, table, or
multiple-occurrence data structure.
62. Using "* "
to reference all elements 3
If the result
represents an unindexed array or an array specified as array(*), the
value of the
expression is assigned to each element of the result
Based
Variables and Dynamic Storage Features
Based variables and dynamic storage allocation provide
greater flexibility in programs. Modern languages, such as Java, take care of
storage management for you. But at least now ILE RPG lets you do such things as
allocate an array with varying numbers of elements. In ILE RPG, based variables
and pointers are the key to dynamic storage and are also necessary to exploit
some system APIs.
Rate your knowledge about declaring and using the
following types of variables, and give a brief summary of your understanding:
63. Pointer variables 2
D MyPointer S *
D String S 100A
/Free
MyPointer
= %Addr(String); //give me the memory address of variable string
/End-Free
64. Based variables 2
D MyPointer S *
D
Struct ds based(MyPointer)
D Element1 10A
D Element2 10A
Rate your knowledge about the following functions and
features, and give a brief summary of your understanding:
65. %Addr function 2
Returns a value of type basing pointer. The value is the address of the
specified variable. It may only be compared with and assigned to items of type
basing pointer.
66. %Alloc, %Dealloc, and
%Realloc functions 2
Memory management
operations.
%ALLOC Function
for allocating storage.
%DeAlloc Function
to free the allocated storage.
%REALLOC Function
for reallocating storage.
67. Pointer arithmetic
(incrementing/decrementing addresses; using offsets with addresses) 2
D P1 s *
D P2 s *
* Allocate 20
bytes of storage for pointer P1.
C ALLOC 20 P1
* Initialize the
storage to 'abcdefghij'
C EVAL %STR(P1:20)
= 'abcdefghij'
* Set P2 to point
to the 9th byte of this storage.
C EVAL P2 = P1 + 8
* Show that P2 is
pointing at 'i'. %STR returns the data that
* the pointer is
pointing to up to but not incuding the first
* null-terminator
x'00' that it finds, but it only searches for
* the given
length, which is 1 in this case.
C EVAL Result =
%STR(P2:1)
C DSPLY Result 1
* Set P2 to point
to the previous byte
C EVAL P2 = P2 - 1
* Show that P2 is
pointing at 'h'
C EVAL Result =
%STR(P2:1)
C DSPLY Result
* Find out how far
P1 and P2 are apart. (7 bytes)
C EVAL Diff = P2 -
P1
C DSPLY Diff 5 0
* Free P1's
storage
C DEALLOC P1
C RETURN
User-defined
Procedures and Functions
Procedures and functions are the fundamental building
blocks for modular programming, a practice that is essential to managing the
development and modification of complex software. If you’re not writing
procedures in your new ILE RPG code you’re about twenty years behind
contemporary programming practices.
Rate your knowledge about defining procedures and
functions, and give a brief summary of your understanding:
68. Declaring a procedure
prototype (PR D-spec) 3
Prototyped calls is the recommended way
to call programs and procedures. Prototype interfaces are also checked at
compile time which gives a higher level of systems integrity.
D
QCMDEXC PR EXTPGM('QCMDEXC')
D
CMD 3000a CONST OPTIONS(*VARSIZE)
D
CMDLEN 15P 5
CONST
D 3A
CONST OPTIONS(*NOPASS)
D
VAR1 S 200
C EVAL VAR1 = 'WRKSPLF'
C CALLP QCMDEXC(VAR1:%LEN(VAR1))
C EVAL *INLR = *ON
/FREE
QCMDEXC
('WRKSPLF' : %SIZE ('WRKSPLF'));
/END-FREE
69. Defining a procedure
— Begin-procedure and End-procedure specifications (P-specs) 2
P
FormatAddress B
D
FormatAddress PI 45A
D
City 20A CONST
D
ProvParm 20A CONST OPTIONS(*NOPASS)
D
Province S 20A INZ('Ontario')
*
Set the local variable Province to the value of the second
*
parameter if it was passed. Otherwise let it default to
*
'Ontario' as it was initialized.
C
IF %PARMS > 1
C
EVAL Province = ProvParm
C
ENDIF
*
Return the city and province in the form City, Province
*
for example 'North York, Ontario'
C
RETURN %TRIMR(City) + ',' + Province
P FormatAddress E
70. Declaring a procedure
interface (PI) D-spec 2
As above.
D
FormatAddress PI 45A
71. Declaring procedure
parameters (basic techniques) 2
D
RPGHDLR PR
D
Parm1 LIKE(CondTok)
D
Parm2 *
D
Parm3 10I 0
D
RPGHDLR PI
D
InCondTok LIKE(CondTok)
D
pCommArea *
D
Action 10I 0
D
OutCondTok LIKE(CondTok) D Parm4 LIKE(CondTok)
72. Declaring and using
data structure parameters 2
To define a prototyped parameter as a
data structure, you must first define the layout of the parameter by defining
an ordinary data structure. Then, you can define a prototyped parameter as a
data structure by using the LIKEDS keyword.
73. Declaring and using
array parameters 2
D
Address
DS
DIM(20) QUALIFIED
D
Street
30a DIM(2)
D
City
20a
D State
2a
D
Zip
5a
D
ZipPlus
4atorage
74. Declaring and using
variable-length parameters (*VarSize option) 3
Please
see point 68
75. Declaring and using
variable-length character-string parameters (*VarSize and *String options) 1
Pass a character value as a null-terminated string. This keyword is valid
only for basing pointer parameters passed by value or by read-only reference. When
OPTIONS(*STRING) is specified for a basing pointer parameter passed by value or
by constant-reference, you may either pass a pointer or a character expression.
If you pass a character expression, a temporary value will be created
containing the value of the character expression followed by a null-terminator
(x’00’). The address of this temporary value will be passed to the called
program
or procedure.
76. Choosing when to pass
parameters by value vs. by reference (Value keyword) 2
Passing
bulky data strings of parameter by value is an ‘expensive’ option when it comes
to performance. When one uses the by reference option, only the reference
pointers are passed where the program being called would be able to allocate it
directly from memory.
Using
the value keyword, one passes the data values as parameters exactly as is where
the receiving program must have the exact receiving data types. It is a safer
option if data in memory are changed between both the calling and called
program.
In Java, the following data types can
only be passed by value:
boolean
byte
int
short
long
float
double
Parameters of these types must have the VALUE keyword specified for them
on the prototype.
77. Declaring and using
read-only parameters (Const keyword) 2
To specify the value of a named
constant and to indicate that a parameter passed by reference is read-only.
Dprocedure PR
D Parm1 10 A CONST
D Parm2 10 A CONST
/free
Proccedure('ABC' : '123'); //The receiving
procedure gets a constant value, which cannot be
//changed
/End-Free
78. Declaring and using
optional parameters (*NoPass and *Omit options) 2
* When OPTIONS(*NOPASS) is specified on a definition
specification, the parameter does not have to be passed on the call. Any
parameters following that specification must also have *NOPASS specified. When
the parameter is not passed to a program or procedure, the called program or
procedure will simply function as if the parameter list did not include that
parameter. If the unpassed parameter is accessed in the called program or
procedure, unpredictable results will occur.
Please
see point 68
When OPTIONS(*OMIT) is specified, then the value *OMIT is allowed for
that parameter. *OMIT is only allowed for CONST parameters and parameters which
are passed by reference.
Dprocedure pr extpgm('PROGRAM')
D
parm1 10
A Options(*NoPass:*Omit) Const
D
parm2 10
A Options(*NoPass:*Omit) Const
79. Declaring local
variables in a procedure 1
Local variables are declared within the
sub-procedure definition.
80. The difference
between local vs. global scope of identifiers 1
In general, all items that are defined
in the main source section are global, and therefore, known throughout the
module. Global definitions are definitions that can be used by both the main
procedure and any subprocedures within the module. They can also be exported. Items in a subprocedure, on the other hand, are local.
Local definitions are definitions that
are known only inside that subprocedure. If an item is defined with the same
name as a global item, then any references to that name inside the subprocedure
will use the local definition.
81. The difference
between static vs. automatic storage for local variables (Static keyword) 1
For a local variable of a subprocedure,
the STATIC keyword specifies that the data item is to be stored in static
storage, and thereby hold its value across calls to the procedure in which it
is defined. The keyword can only be used within a subprocedure. All global
fields are static.
If STATIC
is not specified, then any locally defined data item is stored in automatic
Rate your knowledge about implementing procedures and
functions, and give a brief summary of your understanding:
82. %Parms function 3
Number of
parameters passed to procedure.
P MaxInt BD MaxInt PI 10I 0
D p1 10I 0 VALUE
D p2 10I 0 VALUE
D p3 10I 0 VALUE
OPTIONS(*NOPASS)
D p4 10I 0 VALUE
OPTIONS(*NOPASS)
D p5 10I 0 VALUE
OPTIONS(*NOPASS)
D Max S 10I 0
INZ(*LOVAL)
* Branch to the
point in the calculations where we will never
* access unpassed
parameters.
C SELECT
C WHEN %PARMS = 2
C GOTO PARMS2
C WHEN %PARMS = 3
C GOTO PARMS3
C WHEN %PARMS = 4
C GOTO PARMS4
C WHEN %PARMS = 5
C GOTO PARMS5
C ENDSL torage
83. Return expression
opcode (to return a function result) 3
The RETURN
operation causes a return to the calling program.
C RETURN
If a value needs to be returned to the
calling program, the return value must be specified in the expression operand.
C RETURN 'L'
Rate your knowledge about calling procedures and
functions, and give a brief summary of your understanding:
84. CallP opcode 2
To call a
prototyped program or procedure written in any language.
D AddName PR
D name_parm 40A
D Display PR
D Free PR
C CALLP AddName(name)
C CALLP Display
C CALLP Free
85. The difference
between a dynamic program call (Call or CallP) vs. a static procedure call
(CallB or CallP) 2
Dynamic - The CALL operation passes
control to the OPM program specified in factor 2. Validation is done at compile
time (e.g. program parameter/s).
The compiler cannot perform type checking on the parameters, which may
result in run-time errors.
Static - The CALLB operation is used to
call bound procedures written in any of the ILE languages.
Validation is done at runtime.
Run-time performance is faster.
Allow operational descriptors, omitted parameters, and they extend the
limit (to 399) on the number of parameters that are passed.
Source
Code Inclusion Features
Code reuse is one of the simplest, yet most powerful
techniques to save time and improve consistency.
Rate your knowledge about the following source code
inclusion features, and give a brief summary of your understanding:
86. Option( *NoShowCpy )
keyword on H-spec 2
Specifies the
options to use when the source member is compiled.
Do not show source
records of members included by the /COPY compiler directive.
This will affect
debug.
87. /Copy compiler
directive 2
When coding a module with multiple procedures, you will want to make use
of /COPY files, primarily to contain any prototypes that your application may require.
If you are creating a service program, you will need to provide both the service
program and the prototypes, if any.
88. /Include
compiler directive 2
The /COPY and /INCLUDE compiler directives cause records from other
files to be inserted, at the point where the directive occurs, with the file
being compiled. The inserted files may contain any valid specification including
/COPY and /INCLUDE up to the maximum nesting depth specified by the COPYNEST
keyword (32 when not specified).
These directives have the same purpose and the same syntax, but are
handled differently by the SQL preprocessor. If your program does not have
embedded SQL, you can freely choose which directive to use. For SQL use
/INCLUDE.
89. /Eof compiler
directive 2
The /EOF directive tells the compiler
to ignore the rest of the source lines in the current source member.
Enhancing compile-time performance when
an entire /COPY member is to be used only once, but may be copied in multiple times.
(This is not true if excluded lines are being printed).
Conditional
Compilation
Conditional compilation is another simple technique
that’s immensely useful for testing, problem diagnosis, and expanded code
reuse.
Rate your knowledge about the following conditional
compilation features, and give a brief summary of your understanding:
90. Option( *NoShowSkp )
keyword on H-spec 2
Do not show ignored statements in the
source part of the listing.
The compiler ignores statements as a
result of /DEFINE, /UNDEFINE/IF, /ELSEIF or /ELSE or /ENDIF and /INCLUDE directives.
/EJECT directive does not cause a page break. Similarly, /SPACE, /TITLE, /COPY
and /EOF compiler directives are ignored if they are encountered; instead a
message is printed giving the number of lines excluded.
91. /Define and /Undefine
compiler directives 1
Please see point 90
The conditional compilation directive statements allow
you to conditionally include or exclude sections of source code from the
compile.
Condition-names
can be added or removed from a list of currently defined conditions.
92. /If, /Else, /ElseIf, and
/EndIf compiler directives 1
If the condition expression is true, source lines following the /IF
directive are selected to be read by the compiler. Otherwise, lines are
excluded until the next /ELSEIF, /ELSE or /ENDIF in the same /IF group.
93. Define parameter on
CrtBndRpg and CrtRpgMod commands 3
Create a Bound RPG Program - With this
command you can create one of two types of ILE programs:
1. OPM-compatible
programs with no static binding
2. Single-module
ILE programs with static binding
Create RPG Module (CRTRPGMOD) command. This command compiles the source
statements into a module object. A module is a nonrunnable object; it must be
bound into a program object to be run. To bind one or more modules together,
use the Create Program
(CRTPGM) command.
Create a module using the Create RPG Module (CRTRPGMOD)
OS/400
ILE Modular Programming Features
To practice modular programming with ILE RPG, you must
understand related OS/400 ILE features for creating and running programs and
service programs.
Rate your knowledge about the following OS/400 ILE
features, and give a brief summary of your understanding:
94. Creating a program
from multiple modules (CrtPgm command) 1
The Create Program (CRTPGM) command creates a program object from one or
more previously created modules and, if required, one or more service programs.
You can bind modules created by any of the ILE Create Module commands,
CRTRPGMOD, CRTCMOD, CRTCBLMOD, or
CRTCLMOD.
CRTPGM PGM(MYPROGRAM)
MODULE(*LIBL/MYMODULE1 *LIBL/MYMODULE2 *LIBL/MYMODULE3)
95. Creating a service
program from multiple modules (CrtSrvPgm command) 1
Service programs are a means of packaging
the procedures in one or more modules into a separately bound object. Other ILE
programs can access the procedures in the service program, although there is
only one copy of the service program on the system. The use of service programs
facilitates modularity and maintainability. You can use off-the-shelf service
programs developed by third parties or, conversely, package your own service
programs for third-party use.
CRTSRVPGM
SRVPGM(MYSERVICES) MODULE(MODULE1 MODULE2)
96. Creating a program or
service program with references to procedures in a (different) service program 0
97. Specifying an
activation group for a program or service program 1
ILE programs and service programs are
activated into activation groups which are specified at program-creation time.
The process of getting a program or service program ready to run is known as
activation. Activation allocates resources within a job so that one or more
programs can run in that space. If the specified activation group for a program
does not exist when the program is called, then it is created within the job to
hold the program’s activation. An activation group is the key element governing
an ILE application’s resources and behavior. For example, you can scope
commitment-control operations to the activation group level.
98. Bind-by-copy vs.
bind-by-reference 0
The function of the binder is similar
to, but somewhat different from, the function provided by a linkage editor. The
binder processes import requests for procedure names and data item names from
specified modules. The binder then tries to find matching exports in the
specified modules, service programs, and binding directories.
In creating an ILE program or service program, the binder performs the
following types of binding: Bind-by-copy or bind-by-reference.
99. Exporting
procedure names 1
The specification of the EXPORT keyword
allows a globally defined data structure or standalone field defined within a
module to be used by another module in the program. The storage for the data
item is allocated in the module containing the EXPORT definition. The external
name parameter, if specified, must be a character literal or constant. The
EXPORT keyword on the definition specification is used to export data items and
cannot be used to export procedure names. To export a procedure name, use the
EXPORT keyword on the procedure specification
STRPGMEXP
PGMLVL(*CURRENT) SIGNATURE('MYSIGNATURE')
EXPORT SYMBOL('MyProcdure1')
EXPORT SYMBOL('MyProcdure2')
ENDPGMEXP
100. Using binder
language 1
If the interface to a service program
changes, then you may have to re-bind any programs bound to the original
service program. However, if the changes required are upward-compatible, you
may be able to reduce the amount of re-binding if you created the service
program using binder language. In this case, after updating the binder language
source to identify the new exports you need to re-bind only those programs that
use them.
101. Using a binding
directory 1
A binding directory contains the names
of modules and service programs that you may need when creating an ILE program
or service program. Modules or service programs listed in a binding directory
are used only if they provide an export that can satisfy any currently unresolved
import requests. A binding directory is a system object that is identified to
the system by the symbol *BNDDIR.
Completion
Thank you for taking the time to complete this score
card.