Data structures in RPG (specifically ILE RPG or RPG IV) are powerful tools for grouping related data items together. They provide a way to organize data, improve code readability, and simplify data manipulation. Here's a comprehensive guide to using data structures in RPG:
1. Defining Data Structures :
You define a data structure using the DS
keyword in the Definition specifications (D specs).
Dcl-s MyDataDS Ds; // Basic data structure
2. Subfields :
Within a data structure, you define individual data items called subfields. You specify the name, data type, and length of each subfield.
Dcl-s MyDataDS Ds;
Dcl-s Name Char(20);
Dcl-s Age Int(3);
Dcl-s Salary Packed(7:2);
3. Qualified Data Structures :
For better code organization and to avoid naming conflicts, it's highly recommended to use qualified data structures. This means you access subfields using the data structure name as a qualifier.
Dcl-s MyDataDS Ds Qualified; // Note the Qualified keyword
MyDataDS.Name = 'John Doe';
MyDataDS.Age = 30;
MyDataDS.Salary = 50000.00;
4. Like-named Subfields :
You can define subfields based on the definition of existing fields using the LIKE
keyword. This helps maintain consistency and reduces redundancy.
Dcl-s CustomerName Char(20); // Existing field
Dcl-s CustInfoDS Ds Qualified;
Dcl-s Name Like(CustomerName); // Same type and length as CustomerName
Dcl-s CustNo Int(10);
5. Data Structure Types :
EXTRCD
(Extract Record) or INZ(*LIKEFILE)
keywords.EXTNAME
keyword.
6. Using Data Structures : You access subfields of a qualified data structure using the dot notation: DataStructureName.SubfieldName
.
Dsply (MyDataDS.Name);
If MyDataDS.Age >= 18;
// ...
Endif;
7. Initializing Data Structures:
* INZ: You can initialize subfields when defining the data structure.
Dcl-s ProductDS Ds Qualified Inz;
Dcl-s ProdCode Char(10) Inz('ABC-123');
Dcl-s Price Packed(9:2) Inz(0);?
* Clear: You can clear a data structure or its subfields using the CLEAR
operation.
Clear MyDataDS; // Clears all subfields
Clear MyDataDS.Name; // Clears only the Name subfield
8. Data Structure Arrays:
You can define arrays of data structures, which is very useful for working with lists of related data.
Dcl-s EmployeeDS Ds Qualified Dim(100); // Array of 100 Employee data structures
EmployeeDS(1).Name = 'First Employee';
EmployeeDS(2).Name = 'Second Employee';
// ...
9. Examples :
Dcl-f CustomerFile E K Disk Prefix('Cust_'); // Prefix for record format
Dcl-s CustRec Ds Qualified Inz(*LikeRec(CustomerFile)); // Program-described DS
Read CustomerFile;
If %eof(CustomerFile);
// ...
Else;
Dsply (CustRec.CustName); // Accessing data from the file using the DS
Endif;
// In the calling program
Dcl-s MyCustInfo Like(CustInfoDS);
Call MySubroutine Parm(MyCustInfo);
// In the called subroutine
Dcl-s MySubroutine Pr ExtProc('MYFUNC');
Dcl-s CustData Like(CustInfoDS); // Receiving the DS as a parameter
Benefits of using Data Structures :