0% found this document useful (0 votes)
230 views

PL1 Fundamentals and Data Representation - 02 PDF

Uploaded by

aksmsaid
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
230 views

PL1 Fundamentals and Data Representation - 02 PDF

Uploaded by

aksmsaid
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 303
ee CacTaAmacac Elements of a PL/1 Program sews December 31,2018 \F YOUDO NOT AGREE WTH THESE TERMS AND CONDITIONS, OO NOTCONTNUEWTH THEUSEOF TAS [al SOFTWARE. Bl PORTANT: DATATASK PTY LTO, 16 BUSINESS PARTNERG, AND IT AUTHORIZED DISTRIUTORS (te Licensor) ARE WILLING TO LICENSE DATATRAN (he Stare TO YOU ONLY ON THE CONDITION THAT YOU ACCEPT THE "TERUS AND CONDVTIONS CONTANED IN THS LICENSE AGREENENT AND BY USING THE SOFTWARE YOU AGREE TO) 'BE BOUND BY ALL OF THE TERNS AND CONDITIONS OFTHIS LICENSE AGREEMENT. IF YOU DO WOT AOREE TO THE SENSE TERMS THE ICENEA® INN 79 EMRE THE SAFTWARE TA Voul MLSIEH EVENT Youtaay— E] ng wth is ot 2 Bi Ten ae ein celeltet In this mode, you willok atthe diferent components ofa PLM progam. ‘Youwil examine the general structure ofa PLIt program, the typas of statements that can be used, ‘and ther purpose. ‘ter completing this module, you ill be able to: + Identity the Different Types of PL’ Statements and Their Function + Define the Basic Rules Governing the Stucture ofa PU! Program eet Elenens of PLA Program > Sample Lit Progam CACTACACTA PLII program sample heading PROCESS MAP,XREF(FULL) 5 DECLARE FILEIN INCLUDE —__RECOOL; DECLARE TIME_IN DECLARE HHINSS DECLARE TIME. DECLARE TRANSLATE ‘TIME_IN = TIME ()5 ‘© THIS IS A SAMPLE PROGRAM LAYOUT #/ | Acemment within he program FILE RECORD INPUT; cHaR(9)—INIT(''); cHan(8)—INIT(""); BUILTIN; BUILTIN; 7* GET CURRENT TIME */ J® CONVERT TO HH:MM:SS #/ HHMMSS = TRANSLATE('12: 34:56" , TIME_IN, '123456'); READ FILE (FILEIN) INTO (RECOG1); END SAMPLE; Throughout this course, you wil ciscover how to code PLIt statements. ‘Mouse-over the code in the samsle program fora bref description ofeach typeof statement. Den) Elements ofa PLiA Program > Character Sets | Character | Meaning Meaning Alphabetic characters "af" sign, number sign, and curency symbol Numeric characters Blank Equal sign or assignment symbol Plus sign Minus sign Asterisk or multiply symbol Slash or dvde symbol Left parenthesis Right parenthesis Comma Decimal point or period Single quotation mark Percent symbol ‘Semicolon Colon NOT symbol AND symbol OR symbol Greater than symbol Less than symbol Break character (underscore) Question mark ‘AIL statements are coded by using a character se, hich s subset ofl the avaiable EBCDIC characters. The set of characters ‘most commonly used in PL is called the Single Byte Character Set (SBCS), whichis comprised cf the 60 characters shawn inthe tale onthe lt. There is also a resticted 48 character set and a Double Byte Character Set (DBCS) available, bu his course focuses on the standard 60, Character set. Allthe statements in PLt programs are coded with these characters and symbols. ere) Eenens ca PL Pegan> PL Steers FaACTACicac ‘Statement format and layout j VAR = VAR3 + VARE 5 A= Mull statements pe ine > vaRL = 1; Statement can startin any cua —> TOTAL = VARL ; DECLARE TOTAL FIXED DECIMAL ( 11,2 ) Dem (8) [ee PU sa free-format language tat enables you to code slatements stating in any column within the compiler margin setings, generally columns 2to 72. The compiler wil ignore al statements ouside the margin stings. Each PL statement ends with a semicolon (;), More than one statement can appear on each line, separated by semicolons, but normaly ony ane statement is coded pe ne, Datatrain Eee @ [ vaRl = 1; Statement can startin any columa > TOTAL = VARL ; DECLARE TOTAL FIXED DECIMAL ( 11,2 ) singe statement: ‘Tuliple ines INTIAL (8) ee Hint: Any numberof blanks can be inserted between statements and between the elements ofa statement. ‘Aslatement can span more than on ne. In this case. the continued code can also stain any column within the margins. Colin 4 is Lsualy reserved for cong printer contol characters that are used in formating he complerKisting, een tee Previous Jf Next Lt Sitemes ACT AC ACTaAG Pea ‘Statement keywords DECLARE YARIS FIXED DECIMAL (11,2), VARS FIXED DECINAL (11,2); IF VARLS = vaR2$ THEN D0; T=1¢1 READ FILE (INPUT) INTO (RECL) END} LI statements use a set of commands or keywords that have special meaning tothe PL/t compler. Mest statements stat with a keyword that dents the type of statement, such as DECLARE, IF, o READ, In ths course, you wil examine the syntax of PL" statements, an the set of Keywords that can be used wih each sletement ioe, ‘though these keywords are nol reserved, you should avoid using them for other purposes in your program. For example, a dala Vatiable name should not be used as @ PLI' Keyword. ren Page 7 of 23 Pine X cossay Twp {rit ex Elements ofa PLIA Program xX #MIY_VARTABLE You defn your orn data or vareble names and labels in PL program by using programme-definedidentfers. A name olabel identier mus sats the folowing nes: ~ The first character must be one of AZ @ or - Other characters can be composed af AZ @#§ 0-9 or_only ~ The identfer must nol exceed 31 characte in length Noe that oher symbols canntbe sed ina name o label because they have speil meaning othe comple, nding +=* J & and = rs Lefer oa Et /* Wolds the price anount */ DECLARE AMOUNT FIXED DECIMAL (7,2 ) CHARGE = PRICE * QTY + /# TOTAL PRICE */ <— SALES_TAX; BALANCE = PRINCIPAL + INTEREST; JALANCE - CHARGES; #/ ¢ | Using comment delimiters o remove ‘You can place the comment delimiters around one or more PL!1 statements, as shown above, to prevent execution, without removing the statements from the program. ‘Comments are used to document a program. They canbe placed anywhere within a PL program and are ignored bythe compler. A ‘comment must start with the characters /* and end with the characters */. Comments can contain any combination of characters, induding uppercase or owercase alphabetic characters, for example J* Edit AMOUNTS value. */ Like other PL/t statements, a comment must be coded within the compiler margins and can be continued over multiple lines. Eee ee IPLIt Procedure Blocks PL sa structured language which uses procedure blocks as the basic coding junit. [Every PL program has at east one procedure block to contain the statements ot your program. The start of PLI procedure is denoled by a PROCEDURE statement, andthe end of a procecueis indicated by e matching END statement. Allther PL statements that you cde in your program, except the comple | PROCESS statement, are contained within a procedure block, as shown below: |ENTRY_NANE: PROCEDURE [procedure statement operands) PU" statements END ENTRY NAME |ENTRY_NAME is the label name used to dently the procedure. In alton, here are 2 numberof operands forthe PROCEDURE slatement that tll PLA he typeof procedure being cefned, and how he procedure links to other procecve blocks in your program, These statement elements wil be covered later in the course You wil aso ciscover cher ypes of cade blocks caled BEGIN blocks and DO- arouse. Hint You can abbreviate the keyword PROCEDURE to PROC. ie Coa Ce Declaration Syntax: DECLARE { level } name identifier attributes | A ony required when defining a suture Descitesthe yp of data te being defined Programme. defned ame must be 31 characters cress Examples: DECLARE COMPANY CHAR (15) DECLARE CODES () Gar 6) 5 DECLARE CQUNTL FIXED BINARY (15,0) INIT (@) ; DECLARE INPFILE FILE RECORD INPUT ; DECLARE DATE BUILTIN ; Hint: You can abbreviate the keyword DECLARE to DCL. ‘The PLI DECLARE statement i usd io define the names and atirbutes of data variates, uncton,fles, and ober enties referenced inyour program. These salerenis, which are also called dedratns, can appear anywhere in a PL! arogram, but thay must adhere to the nies regarding soope. ‘Youwilleam more about data declarations andthe basic lypes of data variables used in a PL! program inthe next two medules, Ce QQ Processing Statement Index Glossary Helo Ext | Processing statements eee READ FILE (INPFILE) INTO (RECL); — ¢_|Reacing and wing data recorts toa fle WRITE FILE (QUTFILE) FROM (OUTRECL); om z TOT] = AMTL + AMT? ; < | Calenlatons IF ANT < 100 —EE THEN ANT = ANT + 50; Common poets =a) bo I-11; {ete reesa] ANT = ANT + TOTALS (i END; ‘Most programs perform a rumber of ass, suchas validating dat, peforring cllaton, or updating fs. The PLI language contains an extensive ange of processing statements that are used to perform these tasks. In tis course, you wl examine each ofthe basic PLI prooessing cammancs and see how to use tem. Yu wil also leak atthe processing slalements use ta contr program execon, handle runtime eros, and debug your program. Page 120123 | [°}{0} Previous J Next> ‘aPLi Program > Compiler Statement Ty Compiling statements [The "PROCESS statements used to “PROCESS NAP, XREF(FULL) |<< eee eee [The INCLUDE statements an example o INCLUDE LIB (RECOOL) ;< a preprocessor statement, which used fo induce PU source cde rom aitrary. [The DEFAULT sttementis used to DEFAULT RANGE (*) ALIGNED. sa eka data del aioe. ‘A number of other PL/' statements are used by the compiler to perform some tasks at compile-time only. These statements are processed by the compiler, but they do nat form pat ofthe executable program. The above examles show thee ofthe most common compiler slatements ‘There are @ numberof statements ke KINCLUDE, which are called PL’ pre-rocessor commands. These slatemenis can be used to ‘dynamically generate source code for the program just before compilation. JFACTACR CAG le Summary Inthis male, you looked atthe diferent ‘components of a PLit program, ‘You exarined the general structure ofa PL program, te types of statements tat canbe used, and their purpose, You should now be abl to: + Ideatfy the Different Types of PL Statements and Their Function + Define the Basic Rules Governing the Structure ofa PUI Program Next> ee (alto: December 31,2018 |F YOU DO NOT AGREE WITH THESE TERMS AND CONDITIONS, DO NOT CONTINUE WITH THE USE OF THis fa) SOFTWARE. llPORTANT: DATATASK PTY LO, IS BUSINESS PARTHERS, AND ITS AUTHORZED DISTRIBUTORS (te Licensor} ‘ARE WILLING TO LICENSE DATATRAI he Stare) TO YOU ONLY ON THE CONDITION THAT YOU ACCEPT THE "TERIES AND CONDITIONS CONTAINED IN THIS LICENSE AGREEMENT AND BY USING THE SOFTWARE YOU AGREE To| ‘BE BOUND BY ALL OF THE TERNS AND CONDITIONS OFTHIS LICENSE AGREEMENT. IF YOUDO NOT AGREE TO THE [PENSE TERMS THE LICENSOR 18 NWA |ING TO ICENSE THE SOTWARE TO Yo SiiCM eveENT veuimay [F) FLASH ENABLED eM initreyel te In this mad, you willok atthe diferent ypes of arithmetic data variables and constants used for processing numeric data. You will also examine the syriax of defining these datatypes by using the DECLARE statement, and see haw to assign numeric values to these viable. ‘Alter completing this module, you wil beable to: + Identfy Common PL/t Arithmetic Data Types + Dafne the Attributes of Arithmetic Data Types by Using the DECLARE Slalement + Reoognze he Precision of Arithmetic Data Variables and the Range of Vales They Handle = Code Numan Constants + Define the Concept of Default Arithmetic Attributes Cs Vax Coosa Ce Crm Con ‘Sample numeric variables | /* beclaring arithnetic data variables ... #/ DECLARE PRICE FIXED DECIMAL (5,2); DECLARE STOCK ANT FIXED BINARY (31,0); DECLARE PARTICLECNT FLOAT DECIMAL (5); DECLARE WAVE_LTH FLOAT BINARY (21); /* examples of the formats for arithmetic constants ... */ PRICE = 210,56; STOCK_AVT = 1111018; PARTICLE_CNT = 5.4958E10; WAVELLTH = Il091E-108; Not Binary constants ae general nt represented in PL program, For eet they are eared with he equivalent decimal values. The binary representation of rumeric values in PL is dificult to interpret and is normally not used, Decimal values are much more familiar and are almost aways used to represent numbers ina PL! program. Mouse-over the code to see each type of arithmetic data var nd constant. ewe ATAC™ ACA CAG! ‘Types of arithmetic data Attributes , — Identifier ; [scale] [Base] | Precision oecinal Fived point vata... ¥ v DECLARE NUN FIXED DECIMAL (11,2); Binary Fixed Point pata .., DECLARE Nun FINED BINARY (15,5); Decinal Floating Point bata... DECLARE NuwB FLOAT DECIMAL (6); Binary Floating Point Data ... DECLARE uw FLOAT BINARY (21); Hint: BINARY can be abbreviated to BIN and, kewise, DECIMAL can be abbreviated to DEC. The attributes FIXED and FLOAT cannot be abbreviated. PLM provides four basic arithmetic data types, each of which is used in different ways to store and manipulate numeric data. These data cldaralionsor DECLARE statements, are examples of each ofthe four datatypes. ‘You will (ook at each ofthese examples and examine their attributes and meaning. [eter Page Pu sitet Da Types>Deinal Fae Pot Data FACT ACicac! Decimal fixed point data Attributes DECIMAL Dota vatsble name y The FED ati isrefredto a eel anc indates to PLI that is data es 2 fed numberof its and decimal places. rae nay igi ad head 4 [Peastectvarbe tats. iis ese, NUM canals 1 digi, 2of Te DECIVALatoveistetered to astbe| Julich are decimal places The vues tase andindcateshatumerc aves will | [his variable os orange rm - te sted as cecal mers. cesenees 09 1 95580000 6 ‘Note:The numberof decimal places specified in the precision is also refered to as te scale factor. NUMt declare as a decimal xed point variable. These varables are also refered to as pacted decimal because of the way n which the numeri values ae internal stored. As wih al datatypes in PL, thelist of attributes in @ DECLARE statement are separated by one or more spaces and can generally ‘appear in any order. The onl exception for arithmetic datatypes is thal the precision attrbute cannot be the fst atribute in thelist The maximum numberof igs that you can spect the precision for decimal fixed point varabesis 1. Larter Le SUES ny QACTACACAC DECLARE TOTAL FIXED DECIMAL (15,2); Hint You should always specity an odd number of digits in the precision ofa decimal fixed point variable because ofthe way PL stores the numeric values internally. ‘Decimal fixed point data variables can hold a range of values based on the precision attriute. For example, the UNITS vanable can hold values ranging from -€9,999 to +9,999, {you omit the number of decimal places from the precision, PL’ assumes zero, For example, the QUANTITY variable has seven digits and no decimal places. Datatrain Ho TEES Lior J Ce Decimal fixed point values DECLARE UNITS FIXED DECINAL (5,2); Constant values: 250, -10, 99999 DECLARE TOTAL FIXED DECINAL (15,2); Constant values: -25.90, 5210.55 DECLARE INT_RATE FIXED DECIMAL (9,5); Constant values: 7.22563, 13.00625 DECLARE QUANTITY DECIMAL FIXED (7); Constant values: 87260, 9231820 Hint: You should always speci an odd rumber of digits inthe precision of decimal fixed point variable because of the way PL stores the numeric values internally. rtinins CAC RCT Decimal constants are coded as normal decimal numbers, with or without a sign and decimal point. The sample values llustrate how decimal constants ere coded ina PL progam. ee) Binary fixed point data Identifier Atibutes DECLARE BINARY 15,0) 5 Y y Data variate name The BINARY atte isthe base, indicating tat numeric vais wil be represented end v This datatype shares the FIXED attribute Th (1,0) trou isthe precision and, ke wth the decal fed point data type tre cecal fied point cata type itincictes desorbed previously, and soit has a aed haw many cigs and decal paces the number of tgs and decimal paces. data variable hols. nhs case, NUMZ can hold 1 binary cigs in oa NUM2 is decir as a binary fixed pont data variable. Numerc values for this type of vate ae represented interaly a a seres of binary ones and zercs. These varables are generally only used fr ineger values wth no decimal places. The maximum number of igs allowed inthe precision is 31 Decal and binary fed point data variables are the most common types used fr processing numeric data in business application, oe Ce een Et The precision atibule determines the range of values that binary fied point data vce can hole Fr example, the LINECNT variable can hod values ranging tom 32,767 to +32.767 Datatrain Ed cs > Binay Fad Pot Va W ssex Cosa toe (rant Vee Data Es FIXED BINARY (15, 4); Constant Values : 11001.00108 ( = 25.125) Lool1019.00018 ( = 410.0625) Hint You should always specity elther 15 or 31 cgi in the precision ofa binary fixed point variable because ofthe way PL/I slores the binary values intemally. Binary constants are a soris of onas and zeros that represent the binary value. These are diffe to use in @ PLY program and are generally replaced wih te decimal equivalent valve, ‘The examples above show how you can oade binary values, i required. Note the use ofthe abbreviation forthe DECLARE and BINARY keywords, and the diferent order of tributes. ee rent [ren] ee eee ACT ACCC Decimal floating point data une Identifier Attributes DECLARE NUNS FLOAT DECINAL (6); Date vaabe name The FLOAT atl nists that he cata values The (6) abut is he precision indicating willbe stored 2 a floating point number in wo owimany digs the mantissa component components. The es ete sinicant digi of ofthe data vate holds. in his case, ‘he nuit vale refered toa he mantissa and NUN can hold sigrifcant cigs, the secon isthe exponen ich isthe lter"E™ ollned by 3 postive or negate integer value. The DECIMAL ati fo Noaing point dat nical at he exoonent valve refers toa pone of 10. Tati, the actual cata ‘eis oblaned by multipin the mantissa by 10 the wer ofthe exoonent vale, as show in the exarpes. DECLARE VARI DECIMAL FLOAT (5) ; | DECLARE VAR2 DECIMAL FLOAT (7) ; eg. 1234562 = 1234500 eg. 123457E-6 = 1.234567 NUM is a decimal floating point data varie, Vales for these variables ae store intemal in two components, as shown above GGeneraly, they ae ony used in scientific applicators where very smal or very large numbers ae volved Ther is no decimal pace of scale factor defined in the precision of any floating pont variable because PLIT contol his internally by Using the exponent value, For example, the variable NUNS dedared above can store the value 345.678 as 3A567BE-3, and the value 4,567,800 as 245678E+2 Weare Coed oe Bia lating Pen Dat Y ccxx ces Cie Crim (a Binary floating point data Identifier Attributes DECLARE ume FLOAT BINARY Cay; Data vaste name y v [Again the FLOAT atte ncicaes that data Indes 21 sgricant binary cigs values wil be stored in two corpenents, the mantissa and the exponent. Inthis case, the BINARY atrbute indicates thatthe ‘exponent value refers to power of 2. opposed oa power of 10 for DECIMAL FLOAT data, DECLARE VAR3 BINARY FLOAT (6); | DECLARE VAR4 BINARY FLOAT (5); eg. Ieloloess ( = 1344) eg. 10lLle-28 ( = 5.75) NUN is a binary floating point data variable. Like binary fixed aint variables, numerc values are represented by a series of binary ones and zeros. Ths type of arithmetic variable is also sued to applications requiring large magnitude numbers, andi rarely used in comercial PL programs, The maximum allowed precsios for floating pont data types depencs on the operating system platform. Consul the PLIY manuals for deli. When more conto is required over the precision of numeric operatons, xed aint datatypes ae prefered LTeNeT ery Se QaCTACAC aC DECLARE VARA FIXED DEC (11,2) INITIAL (999.55); DECLARE ARC FLOAT DECIMAL (5) INITIAL (12345615); Hint: You can abbreviate the keyword INITIAL to INIT, ‘There are two basic methods of assigning numeric constants to arthmetc dala variables. The frst method is using a new atribute called INITIAL on the data declaration, This attribute is used to itiaize a data variable to the soecied value beloe tis used in the program. ‘You can contol exaclly when this happens with the use of storage class attributes. Noe that decimal vues are used instead of binary values inthe above examples forthe VAR and VARD variables Datatrain Data Definitions - Arithmetic Data Types > Assigning Numeric Values Index“ clossery ‘Help Exit The second mebnod of assigning numeric constants to arithmetic data variables uses the PL assignment statement. Ths isthe slelement used to assign a constant vale, othe resut ofan exoresio, to a Vala nthe example, its used ito assign numeric values to arithmetic variables. ‘Note that PL/1 does not automatically set the initial value of an arithmetic variable to zero. You must explicitly use the INITIAL attribute or agsignmentslalement in you program to set the dased vale Ltetertn eee fo io Tabata [inary fixed point vaables are almost never declared with any decimal places. This is because binary decimal places can only have certain discrete walues, as these examples lustre: ‘DCL VARA FIXED BIN (15,3); \VARA=0.1008; |" Decimal vlugis 0.5‘ VARA= 0.1108; * Decimal values 0.75. */ VARA=0.1118: /* Decimal value is 0.875 “1 ‘As aesul, you canot assign aval o, for example, 0.614 to varable VARA, ‘because it has no equivalent binary value. PL wil assign the nearest nary ‘valu, based on ts own interna algritm, [Decimal xed pint variables obviously donot have te same problem. Any ‘valid decimal value can be assigned to these variables, so they should aays be used for athmeticexoressionsinvovng necsions wth cecimal laces Troughout his course, you wil see how both decimal and binary fed pont \variabls ae used in PU program, See ae Defauit arithmetic attributes jn 4. lfno BASE attribute explicitly declared Default: ‘DECIMAL fxample: DCL A FIXED (5,2) ; ¢ [DENIAL assumed 2. Ifo SCALE attribute explicitly declared: Default: FLOAT Example: DCL B BINARY (15) ; ¢——_____JFLOAT assumed 3. fino PRECISION attribute explicitly declared: Example: befault: DCL D FIXED DECIMAL ; (5,0) - for FIXED DECIMAL DCL E FIXED BINARY ; (15,0) - for FIXED BINARY DCL F FLOAT DECIMAL ; (6) - for FLOAT DECIMAL DCL G FLOAT BINARY ; (21) - for FLOAT BINARY 4. Ifonly the data name is declared with no Base, Scale or Precision attributes, the default attributes are based ‘on the first letter of the name identifier, as follows: Example: Default: DcL I; FIXED BINARY (15,0) ¢ foes to DCLX; FLOAT DECIMAL (6) $$$ KKaicter tac \When declaring arithmetic data vaiables, there ae res that PL uses to determine all the atibutes of each variable. So ar, you nave loked atthe siuaton where attributes suchas scale, base, and precson are expily dad in the declaration statements. The table above shows some examples ofthe attributes that PLIt assigns by default to a variable ifyou omit any of them. For example, the base altbute DECIMAL is assumed by Pt f you oly incu the scl tribute FIXED. Datatrain eer V(elelN cae INY In this module, you looked at the cifferent types of aritmelic date vaabes and constants used for provessng numer data. Yau aso evained the stax of dfning these cat types by using the DECLARE statement, and discovered how to assign numeric values to these variable. ‘You should now be able to: + dently Common PLI Arithmetic Data Types ~ Def the AtrbuesofArttmetic Data Types by Using the DECLARE Statement - Recognize the Precision of Arthmetic Data ‘Variables and the Range of Values They Hancle = Code Numeric Constants ~ Define the Concept of Default Arithmetic Attributes: Previous Lae eo fACACAGaAC Data Definitions - String Data Types Jo: (BM December 31,2018 |F YOUD0 NOT AGREE WITH THESE TERMS AND CONDITIONS, DONOT CONTINUE WITH THE USE OF THIS SOFTWARE, IMPORTANT: DATATASK PTY LTD, IT BUSINESS PARTNERS, AUDIT AUTHORED DISTRIBUTORS (te Licensor ARE WILLING TO LICENSE DATATRANN (he Sofwat) TO YOU ONLY ON THE CONDITION THAT YOU ACCEPT THE ‘TERMS AND CONOITIONS CONTAINED IN THIS LICENSE AGREEMENT AND BY USING THE SOFTWARE YOU AGREE TO BE BOUND BY ALL OF THE TERNS AND CONDITIONS OF THIS LICENSE AGREEMENT. F YOU DO NOT AGREE TO THE SENSE TERNS THE CENSOR 8 MLN TOEURE THE QMETWARE TA Vel siow EveNT vauiMay [T] Datatrain Ease Page tof30 (CMO) Next» i ofe(t ean tio In this module, you wl examine the definition of sirng dla variables and constants, wrich are used {or processing characer and bt data. You wil also see hv to assign charactor andi valves to these variates, anc how to deine sting cata and picture cata, ‘Aer completing this mote, you wil be abe to: - Recognize Character and Bi Sting Daa Definitions + Define the Altibutes of Character and Bit Sting Data Varables By Using the DECLARE Statement + Code Character and Bit Sting Constants in PLt + Idenfy the Default Atrbutes for Character and Bit ‘String Data Declarations rr Cros tring Data Types > Sample String Variables ‘Sample string variables | DCL NAME CHARACTER (28); DCL REPORTS BIT (6); A factored data deceraton which defines two data variables -FIRSTNAME and SURNAME, [pct Each variable can hold upto 30 characters, DCL PRIVAL PIC '(5)9V.99"; NAME = "John smith"; REPORTS = '1OL101'B; FIRSTNAME = "John"; SURNAME = ‘Smith’; PRIVAL = 123.45; ‘Mouse-over the above code for @ description of each type of sting data, lien free) Data eins Sting Data Tpes> Chater Sngs AC TAC RG TAG DCL —_VARSTR: CHAR (200) VARYING; DCL —FIRSTTINE BIT (1) INIT ('1! 8); Dc. BITSTR BIT (24); Hint: The attribute CHARACTER can be abbreviated to CHAR. PL uses wo types of string date, character and tit. Charecer cai simply a series of characters usd fr storing printing, and ‘manipulating character-based data items. Some examples are a client's name and address, a company name, or a product desertion. ‘The lenth ofa character sing variable is defined in parentheses after the CHARACTER keyword, For example, the DESCR varabe is 50 characters or bytes in length. Te aS aoa] we | Data efits Sting Data Tpes> i Stings Vx Vamsery Cine Cre DCL —_DESCR CHARACTER (50); cL ‘DCL = FIRSTTIME BIT (1) INIT ('1' 8); DCL -BITSTR BIT (24); Hint: The attribute CHARACTER can be abbreviated to CHAR. Bit string data is a series of bit values used for storing and manipulating data af the individual bit level. Each bit value is either OFF or (ON, whichis denoted by a it value of or 1 respectively. {PU you can se the value ofeach bil and perform logical operations anit stings. Ths dala ype is commen used to define one or more indicators, or switches which convo the execution of your program. Datatrain errr [arvius fone | Soe ZACZACI CAC |. Examples of charecer sting constants: ) "WILLIAM FORBES’ Uppacase characters "part # 1235 - out of stock’ ies case nd speci chareders Ia single quotes to apecrin character sting it "THERE'S A NEW ENTRY IN THE FILE’ | nustbe coded vie, as shown. PL wll ove the uplcate quote when the character stings processed, "cacac3"x Hexadecimal representation ofthe character sting ABC Character sting constants are coded asa series of characters suounded by single quctes. The singe qutes are only used for delimiting the character sting and are nat stored with the data ‘Any characer can be used in a character string, incuding uopercase and lowercase characers. the character sing is folowed by an X, as inthe al example above, the sing represents the hexadecimal values of the characters. This canbe usellforinduting non-printable chracesin he value Datatrain Peter Data Definitions tring Data Types > Default Character Atri Index Glossary \ Help Bit ‘As wi ny ate vrcle in PL, characte ting vale is define by using the DECLARE statement ‘The CHARACTER attribute indicates to PL thet this is @ character string variable. If you omit te length, PL’ assumes a default length ‘of one character. In the above example, the declaration of SINGLE is the same as: DCL SINGLE CHAR(L); page 730 | RC] Daa eons SnD Tips tng asians Wx Ysa (ten {rin (et ‘ul’ B Bi sting constants are coded as a sres of ones and zeros, are surounded by single quotes, andar flowed byte ltr B, Like character strings, the single quotes are used for delimiting the bit sting, ‘The B a the end is used to indicate to PLIt that this sa bit tring, nota character sting, Prt ke 2 Q PURE Reps Facer FACT Ate ac PICVAR2 Pac '(5)A99"; PICVARA Pc (8)29V. (2)9"; ‘As wih the sing repetion factor, he pure replton fecor can be used asa shorthand way of speciing repeated codes, ad this canbe used wih bal character and numeric pure specicatons.. |nithe examples, PICVAR' and PICVARZ are equivalent, and PICVAR3 and PICVARS are also identical specfications. aot aE [vec | DCL PRAMT PIC $SS9V.99: Some exanpies of fomating fortis picture varable ae: |] Sot->S857O 0-> $100 9G SHE | YYoucauld also ave used a picture pein factor: CL PRANT PIC (SQV; “Type the code forthe delaraton slement or a picture variable called PRAMT, wich cou be used to format the numeric value 867 into the sin $567.00 Assure the picture variable ony hasta hod values in he range 0.0 to 999.98, and thatthe eating dala sgn foaing ‘Click Check My Answer fo compare your answer othe suggested soluon Len Oa eos Stn Cal ypes > rapig ata enone ZAC ACCC DECLARE (NANEL, NAME2) CHAR (20) INIT (' '); NAEL CHAR (20) INIT (' *); NAME2 CHAR (20) INIT (' '); DECLARE (aT, cost) FIXED DEC (11, 2); DECLARE ANT FIXED DEC (11, 2); DECLARE cost FIXED DEC (11, 2); DECLARE PRICE FIXED DEC (9, 2), ay FIXED BIN (15); FIXED DEC (9, 2), FIXED BIN (15); \Wihen declaring several data varatesthathave common attules, PL enables youto use a factred declaration fama. The common atibues are defined eny once, andthe variable names are ted in parentheses separated by commas, a in exams f and 2 Similaty, you can omitthe DECLARE keyword when defining a nunbe of data varabes wih dilerent ltbules. As shown in example 3, ‘each variable definition is separated from the next by a comma, The last variable must be terminated with a semicolon. Biatatrain Gabe [-treius] Index Glossary Help {Print TEx MERTEN Inthis modu, you examined the dein of sting deta vaables and constants, which reused for grocessing characler and bil daa. You also discovered how o assign character and bt values to these varies, and now io defn sting data and picture data “You should now be able to: + Recagrize Character an Bt Sting Data Defrions - Dafne the Atibules of Character and Bit Sing Data Variables By Using the DECLARE Stateront = Code Character and Bit String Constants in PU - Identity the Default Attributes for Character and Bit ‘String Data Declarations Lr Ysa (onan Cae rm ee OTe H Ce Me do) CSO) Registered to: 18M Valor December 31,2018 |F YOU DO NOT AGREE WITH THESE TERMS AND CONDITIONS, DO NOT CONTINUE WITH THE USE OF THIS [A] ‘SOFTWARE, E IMPORTANT: DATATASK PTY LTD ITS BUSINESS PARTNERS, AND ITS AUTHORIZED DISTRIBUTORS (he censors) ARE WILLING TO LICENSE DATATRAD (the Software| 70 YOU ONLY ON THE CONDITION THAT YOU ACCEPT THE "TERUS ANO CONDITIONS CONTANED INTHS LICENSE AGREEMENT AND BY USING THE SOFTWARE YOU AGREE TO ‘BE BOUND BY ALL OF THE TERMS AND CONDITIONS OF THIS LICENSE AGREENENT. IF YOU DO NOT AGREE TO THE OEMS TERMS. THE LICENSNR S/N TA IPENSE THE SMETWARE TO YC MsiICM EVENT veui way —[¥) Datatrain ea Module In tio ‘inthis mole, you wil lok a he PLI1 operations ‘and expressions thal ae used to compare dala values and expressions, perform arithmetic calculations, and manipula sing data. You wil iso see how the assignment slalement is used to ass the results of calculations or expressions te dala variables, After completing this module, you will be able to: ~ Ideniy How to Use the Definitions of Arithmetic and String Operator Symools + Code Aithmatc and Sting Expressions - Ideniy How to Use PL to Compare Arithmetic ‘and String Data Valves - Define the PLIt Rules Governing the Order of Evaluation Win Expressions = Iden How to Assign the Resuls of PLY Expression o Dala Variables Leen fod Coes es sTACTACRA GAG ‘Sample Expressions X = VARL + VAR2 * VAR3; STRI = STR2 || STR3; IFA=B&C>D THEN Mouse-over the code for a descroton of each type of expression. EE! ns and Expressions So AC AC AGC TAC! TARGET = expression; <—__ Examples of single and multiple assignment statements: VARL = "Xxx"; ‘Assign a constant value 900¢ to variable VARI VARL = VAR2; Assign the value of VAR2 to VARY VARL = VAR2 + VARS; Assign te resul of expressson VAR2 + VARS to variable VAR. ‘Assign te value of varible VARS to each ofthe variables VARY, VARI, VAR2, VAR3 = VARA; vAR2, and VAR3. This i allod 2 mulposesignment, where tho target varcblos are separated by commas. You have seen how the assignment statement can be used lo set the value ofa data variable toa constant arthmaticor sting value, and it.can also be used te assign the result of an expression to one or more date variables Expression can simply be the value of anather data variable, or it can be the result of one or more operations or calulations, The assignment slatement wil evaluate the expression, convert the result the datatype ofthe target variable, if necessary, and assign the resulting value | Symbol Meaning Example of expression ~TOTAL2 AMTL + ANT2 TOTALL - TOTAL? VALL * VAL? VAL3 / VAL4 BASEVAL ** 19 ‘In PUI, caleulations are performed on arithmetic data by using the symbols |'sted above, You can code arithmetic expressions by using ‘one oF more ofthese operators, for example: ANTL + ANT / 168 The prefix operators + and ate used only to change the sig ofa value or expression. They should note confused with adding or subtracting. For example, if the value of TOTAL2 is -0, the value assigned to TOTALS inthe folowing statement wl be +50: TOTAL3 = -TOTAL2; Leet STRL || STR2 gives a character string "ABCDEFGH' STR3 || STR4 glves a character siting '10110001'8 (3)'a" || (3)'B" gives a character string ' AAABBB" The enly operator symbol used by PLI for sting data manipulation i the concatenation symbol |. This operator enables yt jin two or mare character orb sting values togather noone sing. The length ofthe resutng sing i the sum ofthe lengths of the stings being joined For example, the flowing expression result ina character sting oflength9, wth value of ABG-DEFGH STRL || '=" [| STR2 eed Equalto Not equal fo Greater than Less than Greater tran, or equal to Not es than Less than, or equal to Not greater than Exit Example of expression AMTL = AMT2 NAMEL T= NAMED TOTALL > TOTAL2 VALL < 1006 PRICE >= MINAMT PRICE —1< MINAMT QTY < oRDQTY QTY “> oRDgTY Note: The operators >= and are equivalent. Likewise, the operators <= and™> perform the same comparison In atypical rogram, you wl requenty compare the values of two dat variables or expressions. PLM provides a set of comparson ‘operators for his purpose, as shown inthe above table. These operator can be used for bot arithmetic and string data ‘The result of a comparison operation is ether TRUE or FALSE. In PL, this equates to abi sting result of "8 (for TRUE) or 08 (or FALSE} DCE every DCL = -VAL2_—FIXED_DEC(S); VALL > VAL2 —/* Evaluates as true */ VALL = VAL2 — /* Evaluates as true */ VALL <= VAL /* Evaluates as false */ AMTB FIXED DEC(9,2) INIT(1), TOTAL = ANTA + ANB; /* TOTAL = 160,55 */ TOTAL >= ANTA + ANTE /* Evaluates as false */ TOTAL >= 150 /* evaluates as true */ Comparison operators can be use to compare the resus of any two arithmetic expressions involving variables and constants. These examples show how PLi evaluates arithmetic comparisons. The second exarole involves an exoression ANTA+ AMT, wich is ‘evaluated before the comparison takes place. ‘When comparing two expressions wth cfferent atrioutes, PL will convert one ofthe values to malch the others attributes, basec-an rules. Datatrain foe 9 [vee ] = ee Example 1 -bit sting compatson: DECLARE SWA_—BIT (8) __—_INIT (‘O1100001' 8); | Slarngalheleimost bt, theft obits in each string are equal, but when the third DECLARE ‘SWB BIT (8) INIT (‘o1000011' B); bit is compared, they are not equal. ‘The expression SwA = SuB (SwA not equal to SWB) would be evaluated as TRUE and retum a result of "" B. Example 2- character string compaison: DECLARE NAMEL_——_GkAR (1B) INIT HARTIN); eee ct ath DECLARE -NAMEZ CHAR (10)-——INIT ("MARILYN"); _| characteris compared, then NAMEZis less then he Tin NAME, and so NAMIE2 Is eveluated as beng less than NAME’. ‘The expression NANE2 >= NAVEL (NANE2 greater than or equal to NAME1) would be evaluated as FALSE and retum 2 result of 0B. Comparison operators can also be used wit character and tt sting data. When bt stings are compared, PL' compares each bit positon rom et to right in both values, Example 1 ilstrates how tis works Ltewis, two character stings can be compared. ln this case, each character poston compared, one by one, fom lft right in both vals. When comparing two characte strings by using >, >=, < or <= operators, PL willevaluale the result based onthe order of characters inthe coating sequence, Example 2 shows how hs works. ‘Operations and Expres eee Yo (nan Ce rm (ea Symbol Meaning Example of expression logical AND logical OR logical NOT BSTRL & '1'B BSTR2 | BSTR3 “1BSTRE As wel as atthmeli, sting. and comparison operators, PLIt has tree logical operators, which are used to manipulate bit sings. You ‘will naw see how these are used QQ ‘Previous Jf Next> Searle cae ncaa [ix (acca (ie Uri (ba BITA & BITB (expression resutis "0001 B) The logal AND operator compares each it valuein BITA wih te sare bt vale in BITB, an produces 2 result sting ofthe same length, Each bitin the results 21 bt, i both BITA and BITE havea i. Oermse itis 2 Obi. BITA | BITB (expression result is '1111'B) ‘Simaty, the lagcal OR operator cones each it value in BTA with he sare tt value in BITE, and produces @ resutit sting ofthe same lenath, However tis me, each ttn the resus a tit, ether BITA or BITE have @ ‘i otbevise itis a Ob 7 BITA (expression resutis ‘Ol00'B) ‘The logjcal NOT operator smal reverses te bi values contained invariable BTA, Thats, 1 bis are converted to Obi, and vce versa, ‘The way in which these operators wor ilustatec by the above examples. In alton to manipulating bt sng values, logical operators ‘canbe used fo code compound PL expressions. The following example shouss how two comparisons are coded in the one expression by using logical operator A=BRC>D Each comparison A= and C> D is evaluated fst. I the resus ofboth are TRUE, then the expression is also TRUE ('T'}; otherwise, it is FALSE (0B). een) CE ee Index ‘VAR@= VAR@ [| VARI; | |The concatenation operator | joins the values of two string harabes ogee to oma singe sting ‘Type the coe fora statement that uses a sing expresscn involving VAR and VARZ to assign he character valve TIME TRAVEL to variable VAR3, given the following declarations: OCL VARI CHAR(6) INIT( TRAVEL"), ‘VAR2 CHAR(S) INIT("TIME") VAR3_ CHAR(L); Click Check My Answer to compare you answer with the suggested solution. Index Y Giossary Help {Print Evi [Expression resulis 100108 |The logical AND operator evaluates the expression one it positon jt ime and sets each esut bit oi both BITA and BITE. }havea 8 for ratit positon. Ctherwse, the result its for tat bit positon Type the result otis gia exoression, gan te folloving dlraton statements BITA & BITS DCL BITA BIT (5) INIT {'18110'B); ‘DCL BITE BIT (5) INIT ('11810°8); Click Check My Answer o compare your answer with the suggested colton Aer foe J vdex X Glossary T vee Y rict Priority Symbol ** NOT, prefix, exponential 7 prefix prefix- *] ‘mutiplication, division addition, subtraction string concatenation ‘comparison operators logical AND logical OR Note: Operators withthe same priority in an expression are evaluated from lft to right, except forthe priority 1 ‘operators prefix 4, and prefix, which ae evaluated from right to left. Parentheses can be used to. ‘override the default order of evaluation Expressions coded in PL/ can contain @ combination of operators from any af the anthmetc, sting, logical, and comparison operators that you have looked at inthis module. When you code an expression that contains more than one operatr, PL/ uses the table shown above to determine the order which those operators are processed. rr) Datatrain Opts and Exesns> Sen Eveatin [cox (oosey Vien Ure Von 1 Cetaeemeye [oenncermntar | 3. Subtract D from the result. This example sows how PU would evaluate the following expression; A+BtC-D te values assigned tthe vrables were a olows: D=tt ‘then the expression resut would be 58 (54 + 15-11), 15033 | (YO) = VAR2 | THEN VAR2 = VAR2 / VARI; ‘You can use exoressions to perform caleuation or manipulate date, and assign the result to another deta variable, 2s shown in the above ‘examples. Exaressions can also be used in conditional stalements, such as the IF statement. ‘These statements evaluate an expression and execute code based on whether the result is TRUE of FALSE. Wan En peed ATACTACI GAG! ested Answer: ‘VARE= (VARI VARZ)/ VARS; Noe the use of parentheses to cota the order of valuation. lou ote them, he dision VAR2 | VARS woul have been lvalated rst because the dhison operator has a higher pity, [The resut ofthe expression would hen be incorrect. ‘Type the code for statement that could be used to caloulate the total of VARY plus VAR2, and civide the result by VARS. Then assign the final result lo VARS, DCL VARL FINED DEC(9) INIT(S@), VAR2 FIXED DEC(5) INIT(123), VaR3 FIXED DEC(3) INIT(S). VAR4 FIXED DEC(11,2); Click Check My Answer o compare your answer with the suggested soluion [renin Pepeoa]f ve Dat Page 18 ions > Data Type Convers Exit Mixed data types Arithmetic. DECIMAL and BINARY DECIMAL converted to BINARY FIXED and FLOAT FIXED converted to FLOAT String CHARACTER and BIT BIT converted to CHARACTER Hint: PL/1 has few restrictions on using different data types in expressions. However, you should avoid data type conversions, where possible, ta improve program efficiency and reduce the possilty of unexpected results When an expression contains data variables or constants thal have different atrioutes, PL/ will onwert the atrutes of one or more of the data values based ona set of rules. Some ofthese rues are shown inthe lable above, The following example llustates ths process: DCL A FIXED DEC(S); DCL B FIXED BIN(15); DCL C FIXED BIN(15); CHA+B LI wil convert the valu in Ato FIXED BINARY before evaluating A+B. Datatrain Perr > Faking of Dat LACH ACne. acs Examples of padding: pcL PRICE FIXED DECIMAL (7,2); PRICE = 128.95; In this example, the arithmetic constant 128.95 vl be padded onthe left wih eres to ive 0012895 five dg and tuo decal places) when assign othe data varabe PRICE, DCL PART_NO CHARACTER (10); PART_NO = 'ABC-9905' ; Here, the character sting constant ‘ABC-9905' will be: ‘padded on the right with two blanks to give "ABC-9905 * hen assigned tothe sting variable PART_NO. \When assigning values to dat varables, where the ena ofthe vale is ess than the length ofthe target variable, PL wll pa the value being assigned. The folowing applies: + Forarthmetc data, values are padded, or filed, with zeroes on the lef. ~ Forcharacer sting data, values are padded on the right wih banks, ~ For it stings, values are padded on the right with 2er its (08). fe) ag ‘Previous If Nex CO eee eee ea Index“ clossary Help Exit a Eeaeetee | Simiay the valu beng assigned is long than the tage vate, PL wl tuncate he value rithmic dat is tuncted onthe left. Character and bit string data is truncated on the right. When comparing two data items of diferent lengths, PL wil alvays pad the shorter data item withthe aporonriate value based on the ata type, for example, zeroes, blanks, of zero bil, |tisimpotanto remember thal arithmetic tuncalon can cause loss of daa or execution eorsin your program. The precision of aritmetic variables shou always be age enough to handle the expected range of numeric values. Datatrain Pe [ Open wih Ary LaACmaAcicac: FIXED DEC(S,2) INIT( (8)8) , FIxeD DEC(S,2) —INIT( (12)0 ) j HAR (10) INIT (3)C") ) CHAR (5) ITC (CDF (1,1) = arr? (2, +55 (1,2) = aRR2 (2,2) +55 (1,3) = ARR2 (2,3) + 55 (1,4) = ARRZ (2,4) +5 5 (2) = ARRA (1,2) || ARRE (1,3) 5 (2) = aRrd (2,2) || ARRA (2,3) 5 (3) = RRA (3,2) || ARRA (3,3) 5 Aaray aren jst a simple means of dering a group ofidenticel deta tems, PL enables youto perfor operations and maripale data values in groups by using entire arrays or array cross-sections, Inexample 1 the single assignment statement uses aray cross-sections to replace furindvdua assignment statements, PL wil generate the code necessary to process eac ofthe ray elements inthe dimensions where you snc an asterisk subst reference, Pero) ‘Arye an na Sucre > Opens wt Ary fac aci crac FIXED DEC(S,2) INIT( (8)0) FIXED DEC(S,2) —INIT( (12)8.) 5 GHAR (10) INIT( (3)C ')) Han (5) mir( (9) ')) 5 ARRL (1,1) = ARRZ (2,1) + 5} ARRL (1,2) = ARR (2,2) +5 5 ARRL (1,3) = ARRZ (2,3) +5 5 ARRL (1,4) = ARRZ (2,4) +5 5 () = area (1,2) || aRRA (1,3) 5 (2) = ARRA (2,2) || ARRE (2,3) 5 (3) = aRRA (3,2) || ARRA (3,3) 5 ‘When performing array operations, i's important that each dimension cross-section has a consistent number of elements or data items inall the arays being referenced. In example 1, the second cimension of bath ARR and ARR2 must have the same numberof elements. Example 2ilusttaes how you can use arrays witha different number of dimensions provided the numberof elements inthe cross- sedtonsis the same, Leta Index X Glossary X Help Print Anger: DCL TOTALS (5,5) FIXED DEC (9,2); TOTALS (#,*) = 8; oF TOTALS = 8: J¥ou cou aso inlize the ray elements o zero, as folows: DCL TOTALS (5,5) FINED DEC (9,2) IMIT( (25)@ bs “Type the coe ore decaaion sate requed laden an aay called TOTALS wth he ates FIKED DEC (9,2) The aay has two dimensions, each of which has fve elements. You can assume the ower bound of each dimension is 1. Also code the single nd Data Structures > Defining LIKE Per ciosary Y vow X Pat Yeon "Example of LIKE attribute: DCL 1 ENPREC_8 LIKE ENPREC Alte mince stuctres and cata element definitions fam EHPREC are copied ta EMPREC DCL 1 SAVEREC, Al the data element darion fm INPREC. ADDR| 3 NAME, CHAR (28) are copie to miner structure ADRLNS, 3 ADRLNS LIKE —INPREC.ADDR ; Hint: The LIKE attribute is used as a shorthand way of declaring structures which are identical. ‘The LIKE attribute is used as a shorthand method for declaring structures which are identical. PLI will expand these LIKE declarations to include al he minor structures and data elements from te copied structure “These examples show the LIKE attrbute being used al both the majr and mincr structure levels, Data items contained in these ructures have the same atrinutes asthe orginal tems, and are referenced in exactly the same way, for exemple: EHPREC_B.NANE EMPREC_B. SALARY SAVEREC. ADRLNS LINEA Literary err end ATAC AC Bit ‘Simple example of structure of arra OcL 1 STRUCB, 3) ARRL (3,3), FINED DEC (11,2), 3 ARR? (8) HAR (3), 3 ARRZ (5,2) FINED DEC (3); ‘Stustures canbe arrays i thir own right. They are then refered to as an array f structures The frst example shows STRUCA being defined es an aray. Each element of the aay isa minor stucure,hocng tems TOTALX, TOTALY, and CODE, These dat items nherthe dimension eltibute and are also arays. As the examples isa, they ae referenced by using qualified names and subscris. You can aso refer to the structure sey using subscripts, ‘The subscriots can follow the structure name or appear at the end of the qualified name, Lerten i EEE [ Terminating Pr EXTPGH: PROC; DECLARE statenents Processing Statements —— CALL PRocD; PL/1 Statements in PROCD ... END PROCD; PROCE: PROC ; < PL/1 Statements in PROCE RETURN; END PROCE; END EXTPGH; ‘The RETURN statements ditferentated by the following: = Itneed not be te last statement ina procedure + Itcan appear more than once in procedure = Itcan also be used to return data tothe caling procedure (Other commands that are used to terminate a procedure ate STOP or EXIT. A procedure is also terminated ven the grogram is. cancalled due to an eror conto, Datatrain errr) CA MAINPGN: PROC OPTIONS (WAIN); DECLARE statements... bis pedo eps oooh DCL EXTPGM ENTRY ( CHAR(S), BIT(L) ) ——jits enclosed in parentheses, anda comma EXTERNAL; sepatales each set of argunent attbutes. DCL VARA CHAR (5); DCL VARB. BIT (1); The CALL statement coniins alistof Pree Statements... |tnedlaens bong pase, ecsed in parentheses. These arguments can be daa variables orconsans, END NATNPGH; The PROCEDURE sialon beng > EXTPGH: "PROC (PRIA, PRIB) | ——— invoked has ait fr data tes oF parameters that are being passed tit, DECLARE statenents DCL PRA CHAR (3) DCL PRNB BIT (1); Processing Statements ... RETURN; J The parameters must ako be decared 35 data variables with matching attributes, However, the cats rames canbe diferent tothove used inthe cling procedure. END EXTPGN; When intemal or extemal procedures are called, you may wanto pass dlato them so that some function canbe performed wt he cata values. n PL, youcan do this by extening th stlerenis relating to procedure blocks. In the above example, the main procedure MAINPGM cals the extemal procedure EXTPGM, and passes the two data items VARA and |VARB. The invoked procedure EXTPGN can then access the values passed by using the decarations for PRMA and PRMB. LYON Program eo) Index Glossary Help {Print exit V MAINPGH: PROC OPTIONS (MAIN) ; DECLARE statements ..... DCL EXTPGN ENTRY ( CHAR(S),BIT(1)) |The RETURNS airbus used to RETURNS( CHAR (5) ) spect the atirbutes of te data tem EXTERNAL} being retuned fom the caled procedure. CL VARA FIXED DEC (5); DCL VARS BIT (1); DCL VARC CHAR (5); Thisis the primary method used to Processing Statenents ... reread "a = THN (AR, AB); — reuminga data value, andi used instead of the CALL statement. DECLARE statenents - DCL PRIA OUR (5): RETURNSis also used onthe PROCEDURE. CL PRwB BIT (1); statement ofthe called procecuret ist the DCL RETVAR CHAR (5); atrioues of the data being relumed Processing Statenents ... RETURN (RETVAR) ; ——— The RETURN statement isused pass back the value of the data item RETVAR to he invoking proved, In addition o data items being passed to procedures as arguments, a dla item can berelumed by te ced procedure, Procedures that ‘elu a valu to tha caling procedure are called funeton procedures, There are addtional PL operands and statements used for this purpose, In the above example, the value relurned by EXTPGM is assigned tothe variable VARC in the main procedure, Natce the use ofthe ASSIGNMENT statement to invoke the functon procedure. rk CALL PRA ARGT,ARG2); TRG3 = PRB ARCS), [The rstprocedure PRA is invoked wih a CALL slaterent anda isto arguments, a shown, The second procedure PRB is evoked wit an ASSIGNVENT statement because a vale is being ets, Note that function procedures, such as PRB, can also be invoked pith 2 CALL statement ors part ofan exression; however, iss ‘Type the cove for the statements required to invoke the two external procedures PRA and PRB, given the following declarations, ‘Assume thal the arguments for PRA are variables ARG! and ARG2. For PRB, the argurnent is variable ARGS. PRB isa function procedure that wil also return a value to variable TRG3, DCL PRA ENTRY (CHAR(S) ,CHAR(3)) OCL PRB ENTRY( FINED DEC(3) ) RETURNS( CHAR(1) ): OCL ARG] CHAR(5), —ARGZ_-««CHAR(3), —ARG3_— «FIXED DEC(3); OCL TRE CHAR(I): Click Check My Answer to compare your answer wih he suggested solution, Datatrain Me Program Flow Con LACT ACACAG) Example of BEGIN block within main procedure: NAINPGH: PROC OPTIONS (MAIN) ; DECLARE statements .. Processing Statements ... {BEGA:} BEGIN; Statenent 1 enn Statement 2 hen contol reaches the = BEGIN statement END {BEGA}; Wore statenents in MAINPGY ... END UAINPGM; The BEGIN books an intemal PL book thats used to grcup statements together. ls delimited by a BEGIN statement and a rmalching END siatemnt, label prt is optional and ithis is used on the END slalemenitmust match he label on the corresponding BEGIN statement. BEGIN blocks df from procedure blocs in thatthe statements willbe executed when the BEGIN statement is encountered during ‘normal program fiow rather than through a CALL statement. BEGIN blocks are only used for condition provessing when block of statements is tobe executed asa result of some exception contin occuring in the program. See toon Voony Viop Uhm en Example of GOTO statements and labels: Oty ree Label names sachet PL es ° atl aay (0); ‘| ta ane ies ane ste + |th acon Ale general appears nore statenents EEE De Se ec eee processing, LABt, Processing continues rom tat statement ‘You have seen how labels are placed on PROCEDURE statements to identify the procedure or entry name. With a few exceptions, labels canalso be pleced on any statement in your program. ‘ne purpose of satan! abel sto provide a reference forthe GOTO salen, hich enables you to branch o another pon your program and continue program execution at that point Coe) SS Yin (comms Cin Von V Example of GOTO statements and labels: um renee Label names must adhere to the PLIT rules + Vaal = ARR (1); relating to name idenifiers, and must end ' with a colon. A label generally appears n Prior othe statement being referenced. GOTO LaBl; next statement ... This GOTO statement wilintemupt normal sequential processing, and tral conro back othe statement beled LABt. Processing hen coninves fom thal statement GOTO statements can also branch between active procedure blacks, or in and out of BEGIN blocks, but this is considered to be poor practice. Even though the GOTO statements a simple method of branching, its an unstructured way of controling the ow of your Program. "Net, you wl look at some mere studtured methods of branching in your PLIt program by using conditional statements and do-groups jatatrain Srl > Condon Stem Vax Varsay Cen Urn Von fa cul General format of an IF statement; The expression in an IF statement canbe any PL expresson tha ruts to, ors comer to, ait stingresut, Nan IF expression ————— be any vai combination of operalios and expressions, including comparisons between dala items or expressions. The PL staterient associated withthe THEN keyword wil be THEN statement block; —— executed ifthe expression in the IF statement evaluates to TRUE, Intis case, the ELSE stterent is cl executes The PU sttrert ssocald wih he ELSE ya wits eeaed fhe exressinin te semen erates fo {ELSE statenent block;} — False inthis case the THEN statements ignced. The ELSE oy and sllemet sk canbe oie iad. The IF statements use to condtonaly execute one or mare statements based on the result a speced conten. Instead of sequently executing every statement, he IF statement enables you to control which statements are executed in your program, When an IF slatement is executed, the expression is evaluated. its tue, the statement block attached tothe THEN keyword is executed; others, he stalemenis forthe ELSE keyword, if present, are executed Datatrain Se (aC AC ica Examples of IF statements using simple and compound expressions, and nested IF statements: | /* Siaple exoression */ TF VARL = VAR2 THEN MSG ELSE MSG VALUES ARE EQUAL’ ; VALUES ARE NOT EQUAL’ S /* Compound expression */ TF VARL > VARZ_ & VAR3 = VARA THN T= T+ 1; /* Bit string expression */ IF FIRST_TIME THEN CALL PROCA; ELSE CALL PROCB} /* Nested IF statements #/ TF VARL 7% VAR2 THEN IF VAR3 >= @ | VAR3 < VARS THEN VAR3 = VARS + VARB; ELSE} ELSE VAR3 = VARG; ‘The above examples show haw the IF statement canbe usedin a PLI program. When he THEN or ELSE statement has been ‘executed, processing canines with the nex! sequen slalementin he program, IF statements can be nested, as shown in the last example. In this cteumstance, you must ensure that all THEN and ELSE statements ‘are alvays matched tothe correct IF statement. As this example shows, it may be necessary to insert a nul THEN or ELSE statement obtain the ight matching, Dee Ya (cman (me Cr Vea General format of a SELECT statement: “The expresso in be SELECT statements optional and canbe any vaid PLN expression, which s evaluated and SELECT { ( expression ) }; | saved. The result ofthe exoression can be any data type. WHEN ( expressionl { ,expression?,.... statement block; WHEN ( expression3 { ,expressionf, .... statement block; ach WHEN slaterent contains one or mote ‘expressions separtedby commas. These ‘expressions are compared, one by oe, tothe saved resi ofthe exressin inthe SELECT statement, or ane evaluated as = oondtionl pression. statement block; } < ‘The sitemens tached to he OTHERWISE Keyword wil ony TESS ‘be executed if none of the WHEN expressions was selected, Hint: The keyword OTHERWISE can be abbreviated to OTHER SELECT stlemens enable you to perform diferent actions depending onthe value ofan expression and ae @ mae flexible metod of cnitling program execution. A select groups delimited by a SELECT slalement and a matching ENO statement. There can be several WHEN statements ina select group, Each WHEN slatemient species one or more expressions separaled by commas. These expressions are evaluated and compared, one by one, with te result ofthe expression in the SELECT statement Wien a match is found, he statements attache to that WHEN keyword are executed: oterwise, the statements attached to the OTHERWISE keyword are executed. Datatrain Prec Yessy vp rit T bat Examples of SELECT statements: SELECT (VARA); WHEN ("VALUE 1" ) T=1+]j WHEN ('VALUE 2', 'VALUE 3!) y=34]j OTHERWISE Keke] 240; SELECT; WHEN ( VARA < VARB ) VARC = ‘LESS THAN! ; WHEN ( VARA = VARB_) ARC = "EQUAL TO"; WHEN ( VARA > VARB_) YVARC = ‘GREATER THAN’; ‘Only one statement block in the select group is ever executed, This is either the matching WHEN statement biock or the OTHERWISE statement block. Controls then transferred to the slatement following the END statement forthe select group When the expression in the SELECT statements omitted, as in the second examole above, expressions in the WHEN statements are evaluated ike an IF condition, {Wan expression evaluates as true (TB, the stalement block associated with trat WHEN is then executed. oe) Index Glossary Help Y, Print IF VARA >= VARB THEN VARC= VARA ; ELSEVARC=0; |The expression inthe IF statement is evaluated and if tue, the |tterient tached tothe THEN keyword is execute. itis ase, Ite ELSE stalerentis executed, ‘Type the code forthe IF statement that could be used o assign the value of VARA to variable VARC, ony the cunt value of VARA is grater than, or equal to, the value of VARB, Otherwise, aig te value 2eo to variable VARC. DCL VARA FIXED DEC(15,2), ARB. FIXED DEC(15,2),, ‘VARC FIXED DEC(15,2); Click Check My Answer to compare your answer with the suggested solution. Datatrai cl Examples of do-groups: IFA=8 THEN 005 <— TeT¢], ARR (T) = ARR (I) + AMT; END; — ELSE D0; Jedel; ARR (J) = ARR (J) + ANTS END | siciemens dled by 00 state SELECT (VARD) | and matching END statement wHEN (1, 3, 5) 0; <—_ VARE = "ABC! VARE = 1; 0; wHEN (2, 4, 6) 00; ARE = "DEF'; VARF = 2; END; ‘So far you have looked at conditional statements where only one statement is executed for each conditon. In addition to BEGIN and procedure bocks, PLT provides a statement bloc called a do-group that contains one or more slalements thal are executed as a group. ‘Do-groups enable you to code any number of statements within an IF or SELECT statement, as shown in the above examples, and are also a powertl tool that can be expanded to execute te statements contained inthe black many times, Pa Inthis module, you examined the PL statements: ‘hal are used to control the execution of a PL/t ‘program. You explored the block structure of PL/1 and the statements se for procedure blocks, do- groups, begin blocs, branching, and conditional processing. ‘You should now be able to: + Recogtize Blocks and Do Groups = Code PL! Statements ~ Recognize Internal and External Procecures + Idanify How to Invoke and Terminate a Procedure + Idanify How to Pass Data Between Procedure Blocks + Code PL! Conditional Statements + Idntfy How to Branch and Use Statement Labels Ys (oan Cee on Ue Iteration and Looping edt: 18M Yolo. December 3, 2018 ‘IF YOU DO NOT AGREE WITH THESE TERMS AND CONDITIONS, 00 NOT CONTINUE WITH THE USE OFTHIS [a] SOFTWARE. IMPORTANT: DATATASK PTY LTD, IS BUSINESS PARTNERS, AND TS AUTHORIZED CISTRIBUTORS (he Licensor) ARE WILLING TO LICENSE DATATRAIN ithe Software) TO YOU ONLY ON THE CONDON THAT YOU ACCEPT THE ‘TERS AND CONDITIONS CONTAINED IN THIS LICENSE AGREEMENT AND BY USING THE SOFTWARE YOU AGREE TO ‘BE BOUND BY ALL OF THE TERMS AND CONDITIONS OF THS LENSE AGREEMENT. IF YOU DO NOT AGREE TO THE [REUSE TERMS. THE IPENEN 8 UHI TALIPENRE THE STETWARE TYAN WsieM EVENT vou May [] FLASH Module Objectives In this module, you wil ook at extensions to the do- croup, which enable statement blocks tobe executed repetitively in alaop, Statement blocks are commonly refed tos iterative or repetitive do-groups, 0 just c-loops. "You wil also examine the options available for contong trative do-groups, and the advantages of Using this type of processing ‘Aer completing this modu, you wil be able to - ently Hi to Use teratve Do-Grouns + Code the Statements and Operands Required to Define a Do-Loop ~ Identify How Do-Loops Are Terminated + Identfy How Nested Do-Loogs Ae Processed QQ Previous xt Se fac acicac ‘General format: [> 00 WHILE (expression); —> palm pea Feautat | |_| Theslatemens within the erative dooop ae execuled reply erage) STSTERERtS | ervesson| | | 28/ngas the exresson inte WHILE operand is eveualed as mee is FALSE. true. When the result of expressions false, PLIY branches out ofthe | END; do-bop to the next sequential statement after the END statement. next statenent .... <—— Example of 00 WHILE: 1-9; 1-3; DO WILE (I< 1); The expression (< J) wie evalvaed each time te opis executed. Tet+h; nts case the statement inthe c-onp willbe executed thee times ore statements [Dletethe expression eves as fale an the op stented. ‘The fst type of repeive do-graup uses the WHILE operand witha conditional expression, which can be any valid PLi exoression, such as those used in IF and SELECT statements, The expression in @ DO WHILE slatementis alvays evaluate frst on each pass before ay statements wihin the do-oop are execued, This means that the expression is evaluated as false on the lop’ fst execution, none ofthe statements inthe do¥oop wil be executed, ; CX) ‘Previous wey ing > Defining DO UNTIL Loops Yes cons Cas ra Ce General format: > 00 wt. (expression);— Resutof | *°"* expression | statements eae ishuse | |e END} next statenent ... —— The statements wii he iteraivecodoop are execuedrepelively aslong asthe expression inthe UNTIL operand is evaites as ‘alse, When the result of expression is tue, PL branches out ofthe co-bop othe net sequential taterent fer the END statement Example of DO UNTIL: DO UNTIL (I >= J); I=1+]; nore statenents The expression (|>= J) willbe evaluced al he end of te lop nhs case te statement inthe do-oop wil be executed once ony before he exoessionis evaluated ast andthe loops terminated ‘The UNTIL operand is like the WHILE operand except thatthe exoression must evaluate as false forthe statements inthe do-oop to be repeated. The UNTIL expression is alvays evaluated last on each pass, thats, flr the statements within the do-oog have been exeouted ‘As 2 resul, the statements inthe do-oop wil ways be executed atleast once, even if the expression evaluates as true onthe lop's frst execution. You can think of the UNTIL expression as being evaluated when the END statement is processed on each pass of he do- loop. Pagest24 (OVO) ee eee a General format: DO WHILE (expression) UNTIL (expression2); [Resut ofexpessont 8 FALSE Rastogi || tee ——— arrest xeon TRUE, is TRUE and result of statements ‘expression? is FALSE, The statements within the iterative do-loop are executed os repetitively 2s long as expression! is evalualed as rue END; and expression? is evalaie as false, When either the ext statenent ... 4. _ |"esuto espresso is fe, orexression? itu, PLt branches out ofthe do-oop to the next sequential statement fir the END statement Example of DO WHILE UNTIL: 325; DO WHILE (1 <= 3) WTIL (I> 3); I-14]; more statenents |The exression(|<= J) willbe evaluated al the sat of he lop, and the expression (> 2) wilbe evaluated ale end ofthe op. nis case the UNTIL expression wil tninate the op afl fortron END ‘You can combine WHILE and UNTIL operands in one do-foop, as shown above. The WHILE expression‘ ill be evaluated atthe start ofthe loop, and the UNTIL expression2 wil be evaluate atthe end ofthe loop Both expressions mus be satisfied forthe loop to continue, one ea ng> Conte Varies ZAC AC General format: Conte Vrable Statue ‘est Incremental Vive ale ofirtege varable NTVAR Ea endval Otherwise, PL branches ou ofthe doleop. For each Fteraion ofthe loop cher than te fs, the vale inincrval is added to INTVAR before beng compared to endl ee =>00 INIVAR = startval fe To endval BY incrval 35 |\¢ seater than endval Vauectineger |] ay : variable INTVAR i NOT gest statenents Te integer vaabe INTVAR i ritaly se tothe ve pectin ee cone by stra and compared tothe value env. The sialemenis in the lop are repeated as lng as INTVAR is ol greater han next statenent Example of control variables in a do-loop : Dor=1 10 10 BY 2; Intis example, he values assigned to | ae 1,3,5, andso orth, When te value of lreaches 11, the loops teminated because the value of is ereter than the endvalof 10. The sateen inthe loop wl ave been executed five times, statements cont varable canbe used in adofoop to spect the number oftmes thal the statements in 2 lop are executed. General, cota variable is an arithmetic integer varable. The valves assigned tothe contol variable for each iteration ofthe loop are provided by the stating value startval andthe incremental value inerval. The value given in endval isthe upper limit ofthe control varable and is used by PLI to determine when the loop is terminated Altres values, startval, endval, and incval, can be constants or expressions, ra Datatrain Variable Vak Tee General format: cae [arin] [et] [icone DO INTVAR = startval { TO endval BY incrval }; |\aeetineo: vite TVAR Vawoinepr _ 1S greater than ena. Coreen statements The integer variable INTVAR is initally se tothe value specified pemalen hoe by sata and compared io the value env. The stalerents nthe agp are repeated as long as INTVAR i ot greater than or endval. hers, PL branches ou the dolonp, For each next statement ... teraton of the loop oer than the fr the vale in neva added lo INTVAR beer being compared t end Example of control variables in a do-loop DoT=1 10 10 sy 2; Inthis examle, the values assigned to | ae 1,3, 5, and so orth, When te value of reaches 11, the oop is terinated statements | secause the value af ise than he endval of 10. The Paes statements in he lop wl ave been executed fv times ‘The TO endval and BY inerval operands are bath optional. f BY incrval is omitted, an incremental value of one is assumed by PLI1, If TO encval i omited but BY incral is provided, PLt assumes that there is no upper lit valve so you must terminate the lop in some oer way. {170 endvel and BY inal are boh omited, PL assigns a sing sat value, only to the contl variable, before the lop is executed Datatrain Peer iron ad Lapin» up Cot al Rares FaACACncac 00J=1 TO 3, 107016 BY statenents ‘As sho in te above examples, you can specy mle control variable anges for adoloop Each range i sepavated bya comma and it can contain any valid combination of startval, endval, and incrval values. PL wil evaluate each ange sequently fom eta ght, and assign values tothe cont variable accocingly. The loops terinaed only when the last range has been processed. Datatrain rr Ls fac Acicac DOI=) TO (K+) BYK; statenents Do-loops ca teas simple or as complex as required, Any valé combination of cant verabe ranges and WHILE or UNTIL conditions, oath, can be usedin a single iterative dooop statement ‘This gives you complete contol over when and how often the stalemens in your dorloops are executed Dee Sa DOJ=1T0 10 WHILE (TOTAL <= 100) TOTAL = TOTAL + WK/WY): END; [The coniolvaable Js used to epeat the dooop ten mes. The \WHILE expression is evaluated every me the do-bop is repeted, and wil erminat the lop ithe current value of TOTAL is eater {than 100. The END statement dis the do oop slates, Ptr Y gossay X won {rt ext Data declaration: oc. cL. pel. TOTAL = 0; 00 J FIXED BIN(15); TOTAL FIXED DEC(L1,2); VX FIXED DEC(S),, Vy FIXED DEC(3); TOTAL = TOTAL + (WK / WY) 5 ‘Type the cae fr te dooop statements that could be used to repeat he following statements a maximum often times by using @ contol variable J. Also terminal the loa by using a WHILE expresson the value of varable TOTAL exceeds 100. Click Check My Answer to compare your answer vith the suggested solution Laveen er ee ccin __ ample ofthe REPEAT operand ona dooop: DO T=1 REPEAT J / 2 WHILE (I < 100); statements END: Thisis an example of using the REPEAT contol. The expression J 2s evaluated and assigned to the contol variable | before each loop iteration, excep the fst The lop is temineted when the WHILE condtion is sais, ‘The TO endval and BY incrval conirol ogerands can be replaced with the REPEAT operand. This enables you to specify an expression thal is evaluated and assigned tothe contol variable tthe start of each loo9 iteration, exoept the fist. General, the REPEAT contol is used with either the WHILE or UNTIL loop cortos lo specify a conlton that teminates the log Wo n and Looping > Summary of Do-Loop Controls statval,endval, ncrval control variable WHILE condition UNTIL condition REPEAT expression ‘When evaluated Evaluated only once before fst oop. Set to startval oly before frstloop. Incremented by incrval before other loops. ‘Compared to endval before every loop. Evaluated before every loop. Evaluated eter every lop. Evaluated before each loop, except the first, Listed above are the teralve do group cots and when they ae evaluated feat Index Y Glossary Y Help Y print Y Example of GOTO: 00 T= 170 20; statenents: GoTo Las] , ee The COTO statement ul branch out of he Bo oop othe statement beled LAB and thus, terminate any further lop processing. Ul: ample of LEAVE: ue2: 001-170 2; a he LEAVE stent wil aso ranch ott te doo beled 37 the nent sequent aa sttemer loing he ENO sateen next statenent... Hint Your site may have restrictions on using these statements to terminate a do group or iterative dooop. General the oer loop controls covered in ths module are used in preference Do-loops can be terminated in PLT onthe basis ofthe format of the DO statement, This is when one ofthe flowing conditions exists: = The value of the control variable exceeds the upper limit value ~ The WHLLE condition isnot satisfied ~ THe UNTIL condition is satisfied You can also branch out of a doroop with a GOTO statement or by using a LEAVE statement. These statements can be used to terminate any form of ado group or iterative do-oop; however, a GOTO statement cannot be used to branch into a doroop. MAW cope Iteration and Looping > Nested Do-Loo ZACZACI GAC! D0 1 = 170 20; outer do-loop statenents ..... mj=1T05; [' ‘inner do-loop statements ..... ‘Two ormore dooops can be nested. Al the iterations ofthe imr loop are performed foreach tration ofthe outerlop. This is 2 powerful too for eating dooops thal are dependent on each ater, and for processing rays attain Exit ng > Processing Arrays By Using Loops cL RRB (6,3) FIXED DEC(7); Dor=1104; pods) 3 [eomemttones| ARR (1,3) = 0} Dotoops enable youto process arenge of selected ara elements by using the dofoop canal varibles as te subst references for those arrays. Because te contol vaabe values ae maintained by PL! dung each loop tration you can use these variables wth co-op for ‘any operation in which incremented values are required, Aray handing is just one example of thr use. Lene foe Module Summary In tis madue, you looked at extensions tthe do group, whch enable statement biocks to te executed repelivly in alooo. You also examined the optons ‘avaiable fr conling iterative do groups, and the advantages of using this typeof pressing. ‘You should now be able to: - Henify How to Use iterative Do-Groups + Code the Statements and Operands Required to. Define Do-Loo - Henly How Do-Loogs Ave Terminated - Henify How Nested Do-Loops Ave Processed Next» era @ RC rene Index Glossary Print exit Storage Attributes and Scope io BM Vals io: December 31,2018 IF YOUDO NOT AGREE WITH THESE TERNS AND CONDONS, DO NOT CONTIUE WITH THE USE OF THIS [al] SOFTWARE, Bl IMPORTANT: DATATASK PTY LT, ITS BUSINESS PARTNERS, AND ITS AUTHORIZED DISTRIBUTORS he Licensrs) ‘ARE WILLING TO LIGENSE DATATRAIN (he Sofware TO YOU ONLY ON THE CONDITION THAT YOU ACCEPT THE ‘TERNS AND CONOVTIONS CONTAINED IN THIS LICENSE AGREEMENT AND BY USWNG THE SOFTWARE YOU AGREE TO BE BOUND BY ALL OF THE TERNS AND CONDITONS OF THIS LICENSE AGREEMENT, IF YOU DO NOT AGREE TO THE LICENSE TERUS THE ICENSNR SMV LING TOICENRE THE soeTWneRE Ta YoU msi EveNT vouimay LU] proceeding wit 0 the a) FLASH Datatrain Eas Page tot3t (OC) Next oN eM@) Cera Inthis madue, you wil expo the PL atibutes thal define how slorage for dala variables is allocated and managed. You wl also examine the pointer variable and scope, which detemines where you can reference daa vaables in a program. ‘ter completing tis mode, you wil be ale to: - Identify the Types of PL Storage Classes ~ Recognize a Pointe Variable ~ Idenify the Scope ofa Varable ~ Recognize the EXTERNAL Atrio ~ Recognize the ALIGNED Atbute ~ Iently How to Overlay Data Variables By Using the DEFINED and BASED Altivutes + Identify How to Override Default Aitnbutes Page 2 eee ACT ACA CAG) VARC(1), VARC(2), VARC(3) ‘The deta variables, constants, and ether contl variables used ina program occupy some storage or memory area The ameunt of ‘ero required is dleried by the tye of data. For example, VARA sa characle sting variable tha requires len bles of memo. \VARB is a tnary fxd pon aril that occupies tuo bytes memory, and VARCis an ara requiring sixes in total ‘There are several atrbues that you use in DECLARE statements to define when this storage is allocaled, and when variables are initialized. These are referred to as storage class attributes. een eee SS wo Taian Tre (ne Y Se [Examples using the AUTOMATIC ative ) MAINPRC: PROC OPTIONS (NAIK); storage for VARA ad ARR is allcced 5 5 when provedure MAINPRC is activated, DCL VARA CHAR (6) AUTOWATIC INIT("ABCDEF'); @ i ) “© | and treed when the procedure terminates, DcL ARRL (4,2) FINED BIN (15) AUTO INIT( (8)@ ); | Theil vais areas assigned only ‘once when MAINPRC starts. CALL PROCA; ‘Storage fr VARB is allocated each time procedure PROCA is activated uring execution ole progr, a red ech ie the procedure terials. The al valve i also asslgned everytime that PROCA sas. PROCA! PROCS DCL ARB CHAR (3) INIT ("XY2'); ¢ Default storage lass is AUTOMATIC. END PROCA; END MAINPRC} Hint: The attribute AUTOMATIC can be abbreviated to AUTO. Generally, this attribute is omitted, as shown above for VARB, because itis the default storage class. For most data items, the AUTOMATIC attribute isthe detaul storage class and general tis not explicitly delared. This atrioute indicates that storage is allocated to the data item every ime the pracedure ar begin bloc in which is dadared is activated, and feed \When the block terminates. Ifthe INITIAL attrbute is also used for the data item, PLM ntalzes the variable each ime the block is entered, \When AUTOMATIC vables are declared inthe min procedure lock, storages alcated and iialized ony one when the program stats, ands eed when the program fishes, Creer AINE Storage Attributes and Scope > AUTOMATIC Storage Class Examples using the AUTOMATIC attribute | MAINPRC: PROC OPTIONS (MAIN); ‘Storage for VARA is allocated when DCL VARA CHAR (6) AUTOATIC INIT( 'ABCOEF!); oes Scr 6 > | and freed when he procedure DCL RRL (4,2) FIXED BIN (15) AUTO. INIT( (8)0 ); terinates. The inal value f aso assigned when VAINPRC star's CALL PROCA; Storage for array ARR1 is allocated on entry to MAINPRC, | ‘and all elements of te array ae intaize to zero at that te. Storage is feed when NAINPRC terminates. PROCA: PROC; DCL VARCHAR 3) INIT Cw2'); <———_ Storage for VARB is located each te procedure END PROCAS ROCA’ activated dung execution of the program, ane fess each tmethe procecure terminates. The rita values also assigned everytime PROCA slats END MAINPRC} AUTOMATIC variables can be thought of as being attached to a procedure or begin bloc, and they exist only while the block is active. When both internal and external pracedures are invoked, te caling procedure stil remains actve. This means that AUTOMATIC Variables declared in he caling procedure also remain active, The slrage fr these vaviables is only freed when the calin procedure itself terminates. Jaen cere Tee une DCL VARA CHAR (6) STATIC INIT('ABCDEF"); < DeL ARRL (4,2) FIXED BIN (15) STATIC INIT( (8)0 ); <—— ‘Storage is located othe thee data ers VARA, |ARRI, and VARB ony once befere program execution, andthe values ar nitlized athe same me, DCL VARB CHAR (3) STATIC INIT ('xY2'); The STATIC storage clas atrbute indices tat storages located ote data ite only once before program executen and it remains allocated until the program terminates. ithe INTIAL atrbute i used forthe data tem, PLT also intiaizes the verable only once. PL normally creates and inte STATIC. variables a complete, and they frm pat ofthe execuate load modulo. These variates are ays alocaled ad initaized only once, regartless of the procedure or begin block in which they re declared, and thay ext s long asthe program executes. Pex say ven {rt {eat [There are two other special storage classes called BASED and ICONTROLLED. |PL/+ wil not automatically allocate storage for these variables. You can use these atriouis ior variables when you want to manvaly conta the alocation lan release of storage na program. Ihe BASED atioute has many uses in PL programs, bun tis couse you il ony look al the use of BASED variables to overay cere areas of storage in your program. CONTROLLED varles are not covered in this couse, [vou can only spec one strege cass atiribute ona dat tem, hats can ony be one ofthe folowing |- AUTOMATIC, whic isthe defaut STATIC |- BASED | CONTROLLED atatrain nal Index Y Glossary Y Help Y Print exit Y pc. 1 staucl static, 3) STRA— CHAR(IO) INIT ( (10) "#" ), 3 STRB CHAR(B) INIT ( 'DaTE:' ), 3 STRC —CHAR(B) INIT ( 'mn/dd/yy' )s Storage is allocated to STRUCI prior to program execution, and all data lems in STRUCL are initialized to their respective valves at that ie. Storage for STRUCL sony Fed when epost emia. DcL 1 sTaUC2 3) STRD— CHAR(IO) INIT ( (10) '*" ), 3° STRE —CHAR(G) INIT ( 'DATE:' ), 3 STRF = CHAR(8) INIT ( ‘mm/dd/yy’ ); ‘STRUC2 is assigned a default storage clas of AUTOMATIC. Storageis allocated each ime the bockin which tis dedared is acvated, and freed when i terinaes.Althe data tems in STRUC2 ae inilized to thee respective values every tne the block starts executing, As shown in he examples, you can code a storage class ona mejor structure level. This hes the effec of assigning that sorage cass to all the data items within the stucture, thus determining when those data items are intialzed, if at ll ‘You cannot code a storage cass on a minor structure o a data element within a structure, Aer eee ee POINTER; DeL 1 STRUCA, 3 STRA CHAR(IA) 3 STRB CHAR (6), 3 STRC CHAR (8) 5 cL STRB cHAR (24) STATIC INIT(* DL ADDR BUILTIN; PTRA = ADDR (STRUCA); | Assigns the siorage address of STRUCA io pointer variable PTRA, PTRA = ADDR (STRB); Assigns the storage adress of STRE fo poner variable PTRA. Hint The attribute POINTER can be abbreviated to PTR. Each variable or data item referenced in your program is located in a storage area. The location of each storage area is referred to as the address. A pointer variable is used to stor an adress and “point to one of thase areas of storage, and this is declared withthe POINTER attribute. You can set the value ofa pointer varable in a numberof different ways, Se ceed een Ue caesen Y tndex ¥ Glossary Help \ Ei Examples of POINTER variables: Det PTRA DCL 1 STRUCA, 3 STRA cHar(1o), 3 STRE CHAR(6) 3 STRC CHAR(8); CHAR (24) STATIC INIT(" ADDR BUILTIN; PTRA = ADDR (STRUCA); | Assigns he storage address of STRUCA to pointer variable PTRA, PTRA = ADDR (STRB); | Assigns the storage address of STRB fo poinler variable PTRA. Hint: The attribute POINTER can be abbreviated to PTR. ‘These assignment statements invoduce the fs ofthe PU bul uncon that you willok al. The ADDR builtin function ets the ‘accesso the deta tem passed tits an argurent ater you wl seehow tis method of adcessing canbe used ina PL progran. eae Benes ed Index Y Glossary Help Some common PL alignment rules showing where the storage allocation fra data tem can stat Data Type ALIGNED UNALIGNED. BIT ‘Next available byte Next available bit CHAR ‘Next available byte Next available byte FIXED DEC Next available byte Next availabe byte FIXED BIN (1-15) ‘Next halfword boundary Next available byte FIXED BIN (16-31) ‘Next fullword boundary Next available byte | Bvamples: DCL BITSTRL BIT (4) UNALIGNED INIT(*1161'8); DCL BITSTR2 BIT (1) ALIGNED INIT("1'8); Hin: General, the ALIGNED atrbut is more efcient, enabling your program to run faster Stats al the next avable bin ricry and occupies 4 bits. | Stars a the next avaable byl in memory and occupies 1 bt ‘The attules ALIGNED and UNALIGNED speciy where a data tem can statin memory. Al dala items ae assigned one or another of these albus, ether explcly ory dtaut Iino alignment attribute is specified in a DECLARE statement, the default is based on the datatype. For example, string dala types BIT and CHAR have a default alignment altroute of UNALIGNED and arithmetic data types default to ALIGNED. oa ee eee ALONE ate Vox Coeson (mp Cn Von ‘Some common PL/1 alignment rules showing where the storage allocation for a data item can start Data Type ALIGNED. UNALIGNED. SIT Next avaiable byte Next available bit CHAR Next available byte Next available byte FIXED DEC Next available byte Next available byle FINED BIN (1-15) Next halfword boundary Next available byte FIXED BIN (16-31) Next fullword boundary Next avaliable byte Examples: DCL BITSTRL BIT (4) UNALIGNED INIT(‘1I01'B); | Slats at henext avalabe bl in memory and occupies 4 bs. DCL BITSTR2 BIT (1) ALIGNED INIT('L's); Starts al the next available byte in memory and occupies 1 bit. Hint: Generally, the ALIGNED attribute is more efficient, enabling your program to run faster, ee oes eres This table shows some examples of ho storage alignment works. The main impact ofthis atirbute occurs on aggregate dat types, such as structures and arrays, ‘The ALIGNED attribute can cause PLI* to insert padding bytes between data elements to ensure that thay are aligned correctly, Later in this modu, you wil sae how to override the PL default, so that ll data items are either aligned or uraigned. rrToF Datatrain Suggested Answer: Dox YES CHAR() STATIC NT(Y): | [The STATIC abe used when sbrapeis locale ard Iitized onl oncebeore program exeaion “Type the code fore cecaration statement at cov be used to define a character sting aril caled YES, vhic nes an nial value FY. Assume that the length of he variable is one byte, and use a storage cles atrbute to indicate tha storages allocated and iiakesd ony onoe at compe tne. Click Check My Answer to compare your answer with the suggested solution, in faot3t Storage Attributes and Scope > Scope of Variable Deirit Index Glossary Print [NAINPRC:PROC OPTIONS (MAIN); DCL ARB CHAR (10); | PROCA: PROC; >|<—— vans >| <—\!— or varo {eno PRoca; | PROCB: PROC; <—— or var <——c._ vane wy ‘eno Proce; {END MAINPRC; DCL VARA CHAR (25) STATIC. INIT("'); a FIXED DEC (11,2) INIT(@); AZ FIXED BIN (15) STATIC INIT(O); (5) CHAR(3)_INITC (5)(" ") D5 FIXED DEC (7) STATIC INIT(O); ‘The scope ofa dala item in PLI defines where you can reference that tem in he program. General, a variable delared in a procedure block can he referenced anyahere within that black, inducing any internal procedure blocks. For example, VARA can be referenced in the three procedures MAINPRC, PROCA, and PROC, but VARD is declared inthe intemal ‘procedure PROCA so it can only be referenced in that produ. Datatrain Cr Sue ec Index Glossary Help Print ex This table shows where the variables in the previous code example can be referenced: Variable name ‘Scope VARA NAINPRC, PROCA and PROCB vare #1 NAINPRC, PROCB vane #2 PROCA only YARD PROCA only ARE, VARF PRoC8 only Ifyou declare a variable, such as VARB, in two procedure blocks, PL/t will teat them as separate variables, each with unique seope In this case, a reference to VARB in PROCA will use VARB #2, and a reference to VARB in MAINPRC or PROCE will use VARB #1 Data items declared within begin blocks also obey the soap nes listed above, but this snot usually done ina PL program Noe that you cannot declare two data elements withthe same name in the same procedure black Coe) Sige tesard pe > EXTERNAL Ate (aC Aci erac ‘Another attribute that affects the scope of a variable is the EXTERNAL attrbute. A data variable declared with the EXTERNAL attribute in Lis treated 2s a global varable, When declared with the same name identifier and altibutes in more than ane procedure, it refers to the same variable. ‘Any ala ype can bean extemal var, including aggregates such as stuctures or aays. An extemal variable canbe used for sharing daa between external procedures in your rogram. Page t6of31 [OY(0) |__ Example of DEFINED attribute: | ok AL ) GuR (6); DCL a2 —(5)._ GHAR (4)_—_DEFINED (al);-¢—_|C#T#MAA2is mapper over heer tyfes ofthe ccresoncing elemento Al, RO DCL —VARL_—CHAR (1g) STATIC INIT (‘ABCOEFGHII'); DCL VARCHAR (5) DEFINED (VARI) POSITION (6); Example of string over defning, VARZ overlays VARI, staring at characte 6 Hint: The DEFINED attribute can be abbreviated to DEF, and POSITION can be abbreviated to POS. \Wihen you wantto reference allo partofthe same storage are by using two separate varables wih diferent names and abuts, you can overay two or mre data variables ono the same area of storage by using one of wo basic methods, The rst method uses an atroue called DEFINED. The above examples show hew ths is used Varaties dered withthe DEFINED attrbute co nat eccupy any storage ofthe oun, but overly the storage othe target vafabe GGereraly, two variables declared in tis way must be the same arthmeti or stng datatype Storage Attributes and Scope > Overlay By Exit Example of using the BASED attribute to overay storage! 3 TTEML CHAR (20), 3 ‘TEM? Bir (16), 3 TTEN3. CHAR (10); pet STRB CHAR (32) BASED (ADDR (STRUCA ) ); ocL STRC ‘CHAR (10); ia arec(10) CHAR (1) BASED ( ADDR (STRC ) ); Eater, you saw how the ADDR busin function canbe used fo assign a slorage adress to a pointer variable, nthe above example the ‘uncon cused with the BASED altibut o provide the seccnd method of overlaying storage Inthe above example, sting variable STRB does nol occupy any lage ofits nn but overlays the storage of svucure STRUCA Poe) Se ee Fre Y cossay X tte Tre ext | Example of using the BASED attibute to overlay storage: 3 rel CHAR (28), 3 Tez BIT (6), 3 TTEM3 ‘CHAR (19); OcL STRB ‘CHAR (32) BASED (ADDR (STRUCA ) ); cL, TRC CHAR (10); ARRC(IO) CHAR (1) BASED ( ADDR (STRC ) ); The BASED attributes moc flee than te DEFINED atribut because there are no retcions on data toes. You can base any daa item or aggregate over anyother te, regarclass ofthe datatype You must ensure thal he oveday dala item snot lange than the target date. Inte frst example, STR must nt be longer then the total length of STRUCA. Lereetny Ce eae Ee [DCL VAR” CHAR(G) BASED( ADDR|VARA) Used in tis way, he BASED sirae lass abut indicates that [VARS does ot copy storage cis own bu very or redefines the storage for VARA, "You could also use the DEFINED altbut, as shown [DCL VARE CHAR{S) DEFIVARAy, “yp the cove fo th comple data dectaraon fo varibl VARB belo sot ove the fir eight yes fhe storage lected (o VARA. DCL VARA CHAR(1E); DCL VAR CHAR(B) ‘ Click Check My Answer to compare your answer wih the suggested solution, storage Attributes and Scope> Implicit Declarato Index Glossary Help Exit |. Sxapl of mpl declaration | NAINPRC: PROC OPTIONS (MAIN); FP OCL VARA FLOAT DECIMAL (6); |Implicit declaration with default arithmetic atrbutes. DCL VARX FIXED DEC (9,2), VARY FIXED DEC (9,2); CALL PROCA PROCA: PROC; VARA = VARX + VARY; END PROCA; END MATNPRC} ‘When you do not explicitly define all the data tems used in your program with the DECLARE statement, PL/t will automatically define a variable for you. This process is called an impli declaration, Inthe above example i VARA was not explly cetared, it would reeive the atibutes FLOAT DECI6). Ateterni aoe iota | EM) Se eon Index Y Giossary Help Y Print ext | Example of implicit declaration: MAINPRC: PROC OPTIONS (MAIN); ;—P DCL VARA FLOAT DECIMAL (6); [Implicit declaration wi defaut arithmetic atbutes. DCL VARX FIXED DEC (9,2), VARY FIXED DEC (9,2); CALL PROCA} PROCA: PROG; ‘VARA = VARK + VARY; END PROCA END MAINPRC} Impiity defined varables are assigned a set of defaut tbutes according to the atbute rues. PL defines these vaables i the ‘outers rocedure Lock or extemal procedure ofthe progam in which they were referenced Rather than taking default attributes, certain atibutes can be assumed from the context in which the variable is used. This is caled @ contextual declaration. QQ Setting Default Atributes Index Y Glossary Print DeFULT BAKE (4) FD TU G1,05 ematanema| Bit V ‘The DEFAULT sttzrents @ complerinstuction that overrides the PL data atibute rules. Usual, it appears once al the start ofa program ta prvide alored dau fr your st, OA Datatrain tod Module Summary oy Inthis made, you explored the PL atributes that define how storage for data variables is allocated and managed, You also examined the pointer variable a spe, You should now be able to: Identity he Types of PL Storage Classes ~ Recognize a Pointer Variale + Identify the Scope ofa Variable ~ Recognize the EXTERNAL Attribute + Recognize the ALIGNED Attribute = dently How o Ovetay Data Varbles By Using the DEFINED and BASED Atoues - Identify How to Overide Default Attrbutes Moo Index“ clossary ‘Help print \ exit Built-In Functions Regislered to: 16M Vol o> Dacomber 31,2018 |F YOU DO NOT AGREE WITH THESE TERMS AND CONDITIONS, 00 NOT CONTINUE WiTH THE USE OF THs [A] SOFTWARE. IMPORTANT: DATATASK PTY LTD, ITS BUSINESS PARTNERS, AUDITS ALTHORZED DISTRIBUTORS the Licensrs) ARE WILLING TO LICENSE DATATRAN lhe Sotate) 1 YOU ONLY OX THE CONDTION THAT YOU ACCEPT THE TERMS AND CONDMTIONS CONTAINED NTH LICENSE AGREEMENT ANO BY USING THE SOFTWARE YOU AGREE TO| ‘BE BOUND BY ALL OF THE TERMS AND CONDITIONS OF THS LICENSE AGREEMENT, IF YOU D0 NOT AGREE TO THE SENSE TERMS THE ICENSN® 8 NMI TO ISEARE THE SOFTWARE Ta YoU misiCw EVENT youay [I By proceed Datatrain baie Module Objectives In this modu, you wil ook at PL/ builtin functions, hh enable you to perform frequent tasks without coding. ‘After completing this module, you wil be able to: ~ Code the Declaration fara Buln Function ~ Recgrize Common Sting Buln Functions ~ Define the Concepl of Pseudo-Variables + Identify Arithmetic Buin Functions ~ Identify How fo Use Built-In Functions to Retrieve ‘he Date and Time ~ Identify How to Use Buln Funcons to Perform Simple Operations on Arays Ateteenn Builtn Functions > Sample Built-in Fu f£ACmACI EAC ‘Sample built-in functions DATETINE () ; ‘SUBSTR: (VARA, 3,6) ; VERIFY (VARB, '0123456789") ; ROUND (VARC,2) 3 Rounds the artes valve in VARC to 2 cecal paces. SUM (ARRAY(#,#)) 5 Built. functions are provided as part of the PL/4 language and are used for 2 variety of tasks, including arthmetic, string, and storage control operations. This module will cover some cf the common PL/1 uil-n functions. Fora complete list of functions, refer to the PL Language Reference Manual ‘Mouse-over the PL/t builtin functions above to see whal they do, Builtn Functions > BUILTIN Att Index Y Glossary Hela Print Examples of buil-n function declarations: BUILTIN, BUILTIN, BUILTIN, BUILTIN, BUILTIN, BUILTIN Factored decaration: a00R, ate, INDEX, ‘SUBSTR, STRING, VERIFY ) BUILTIN; Al buitn function ae assigned one tribute, regardless ofthe function they perform. Ths isthe BUILTIN atrbute, Buln funetons ‘ae treated Hk a function procedure and can general be used in PL slatements wherever an exqression can te used. For example: X = SUBSTR (STRA, 2, 5); TF ABS (VALL) >= VALD THEN VAL3 = VALL; LiTENenny i SS Fac acai ac Example1 SUBSTR Example2 STRING General format; STRING ( data identifier ) oc. ARRA (5) CHAR (1) STATIC INIT('V','W',"X','Y','2"); ck STRC CHAR (5); STC = sm Ga) -4 iets The SUBSTR function is used to retrieve part of a character orbit string, This will retum a section ofthe string value, starting at the goston speci by the second argument, fra length specifed inte third argurent. you omit the length, SUBSTR wil retum a secon fom te start positon tothe end of he sting ‘The STRING funcion canbe used fo rlum al the elerensin a character ort sting ray or suture asa single sing constant. The Value ofthe stings tre concatenated values ofl the element inthe eagregate wth length equal the sumo athe element lengths. Lae ee co Bult Free Sng Handg Func Tries (cosy (rep (rin (en General frat: STRING ( data identifier ) cL RRA (5) GHAR (1) STATIC INIT('V!, "W!,"X",'¥""2"); cL STRC CHAR (5); SSTRC = STRING (ARRA); ‘The TRANSLATE function wos wih charece stings ony. Inthe above examle, hs function attemps to nd each of the charactrs from the source sing STRO in the search sng 'EFCDAB. Ha mealchis found, the character's changed tothe valu in the same poston in the pac stng't23466 Ino matchis Fund he charac rom STRO rerans unchanged. Al tree sing argurents canbe consans, variables, or expressions. Datatrain Dee [-Prie sexo | Index Y Giossary Help Print Y ext > String Handling Functor | Examples of string handling functions: Example 1 LOW and HIGH Generalformat: Low ( nuneric expression ) HIGH ( numeric expression ) STRA = LOW (4); Value assigned io STRA is 00000000 STRB = HIGH (3); ¢——— ae assigned to STRB is FFFFFFX Example 2 REPEAT. General format: REPEAT ( string , numeric expression ) DCL STRC CHAR (3) STATIC INIT ('xV2"); bh ON FIXED BIN (15) INIT (3); STRD = REPEAT (STRC, N); ——|Value assign to STRD is XYZXYZAYDZ ‘The LOW and HIGH builtin functions are a convenient way of creating characte string constants with '00'X or FFX values, These are the lowest and highest hexadecimal values that a character can have, and are commonly refered to as low values and high values. ‘The REPEAT funaton i iia the sting repetition facto that you lowed a eater, but the REPEAT fundon enables you to use variables forte sting value and te repetition number. Te resulting sting wil alvaysinclde the orginal sing vale so the number of ‘times that the string repeats is N+4, as shown in the above example. Bul Fincon > Sng Lng W rax \ css Ute Vin Ube Example 1 General format! LENGTH ( string expression ) ok, VARSTR CHAR (58) VARYING; beh. L FIXED BIN (15); VARSTR = 'Lord of the Rings’; L = LENGTH ( VARSTR ); Value assigned fo Lis 17 Eatin tis couse, you looked a the VARYING atrbut, tics used to defn a varying lng character obit ting, The length of this type of sting depends on the length ofthe data assigned toi The LENGTH function enables yout reve the length of varying eng sting dala, or any lhe sting exoression This uncon is usolul when processing sting data where the length can change during program execution ee) Sime Data Example 1 INDEX General format: INDEX (string to search , search string ) pa STRA CHAR (12) STATIC INIT (‘BIRDSANDBEES'); POSN FIXED BIN (15); POSN = INDEX ( STRA, "BEE" ); <— Value assigned to POSNis 9 POSN = INDEX ( STRA, 'D’ ); ae assigned lb POSNis 4 because itis he frst cocuence ofthe eter‘ epee! ys _g__ [Vale assigned to POSN is Obecause POSN = INDEX ( STRA, 'TREE' + — ine sting TREE’ was not cund in STRA. The INDEX function searches forthe first occurrence of the second string argument within the frst string argument, and returns the stating positon of the string value, itis found; others itreturs zero, Tis function is used to locate the position of a character or bit sting alu, oro validate that a sting values present in another sng, ‘The INDEX function stops searching when the frst occurrences found. Any ater occurences of the sting are ignored. SS FaACACicac General format: VERIFY ( source string , validate string ) oa TRE GHAR (5); cL Nu CHAR (10) STATIC INIT ("8123456789"); oc. RESULT Fixed BIN (15); STRB = "67235"; ate ssi io RESULT sO because all RESULT = VERIFY ( STRB, NUM ); the characers in STRB were found in NUM. Sea aac ate ssid o RESULT i 4 because the RESULT = VERIFY ( STRB, NUM); <¢—— our character in STRB was not fundin NUM, ‘The VERIFY function attempts to find each character orbit value from the source string, one at a time, in the validate string. If all the character orbit values can be found, it retums a zero; otherwise, it retums the postion inthe source string ofthe fist value not found. This function can be used to conirm that a sting value only contains certain values, orto locale invalid characers or bits ina sting Datatrain eg EE re fo on Pex say Y wa paint Yt |VARB= SUBSTRIVARA,1055 he SUBSTR bitin uncion wil exact te sting vale, staring lat polion 10 for lng of bes. [ecausetis the st ve carci of testing, you could also }have omitted the last operand, 3s in: JVARB = SUBSTRIVARA.10; ‘Type the coe fran assignment siatement using a PL! bitin function that could be used to etract the characters HARDY from variable VARA and assign em to VARB, given te folowing cecaratons: DCL VARA CHAR(14), VARB CHAR(S); VARA = "LAURELANDKARDY' ; YARB 3 Click Check My Answer to compare your answer with the suggested soluion Ley Lec Ml bun Functions > Pedals [ix Vecsary Cie (rin (ba ample 1 Using SUBSTR as a pseudo-variable: ample 2 ‘Using STRING as a pseudo-variable: 1 sTRuCs, FLOL cHAR (4), FLOZ CHAR (3), FLD3 GHAR (3) STRING (STRUCB) = "AAAABBBCCC' «foe ‘The SUBSTR and STRING functions can be used as the targets of assignment stalemens, as shown inthe above examples. When used in ths way, they are called pseudo-vaables because they are coded in place ofa regula variable. Uke funtion procedures, builtin functions canals be used in exaressins nhs case, he retuned value fom te function epaces the reference inthe comparison or lhe expression. The lst exarpe shows haw abun undion canbe used in his way. Datatrain en [won] ve | teens Index Y Glossary X Help Y Exit General format: MOD ( expressionl , expression? ) DCL ALD FIXED BIN (15) INIT (17), VALE FIXED BIN (15) INIT (3), VALF FIXED BIN (15); VALF = oo (WALD , 8):¢ [yates VA 5] ‘Youll now look at two ofthe many aritmetcfuntons provided by PLM. Thefts the ROUND function, which is used o round the resut ofan arthmatic expression, the frst argument tothe precision nccated by the second argument the precision is positive, the umber s rounded tthe right ofthe decimal pont, the value inciting he number of decimal places. |f the precision is negative, the number is rounded to the left of the decimal point. For @ zero precision, the value is rounded to the nearest whole number. The abeve examples Husa each ofthese possi. (ee General format: oD ( expressionl , expression? ) DCL VALD FIXED BIN (15) INIT (17), VALE FIXED BIN (15) INIT (3), VALF FIXED BIN (15); ‘The MOD function is the PL remainder function, which returns the remainder that is left over after expression is civided by ‘expression. Refer tothe PLIt Language Reference Manual or information about other builin arthmatic functions, PL also provides a series of mathematical functions, such as SQRT, LOG, SIN, and COS. Page 14 of 30 Date an Tine EAC™ Atm Gat Example 1 DATE DDCLTODAYCHAR (6) Vale assigned o TODAY isthe curent ate TOOAY = DATE ( ); << Inthe fomat yd (earsronth 9, The yes wo dls and exces the century Example 2 TIME DCLCTIME CHAR (9); ‘Value assigned to CTIME is the current (CTIME = TIME ( )j fine inthe format hhmsstt (hous, mits, seconds, ilisecons). Example 3 DATETIME ee Ta Va asigns i CDATETM isthe outdo COATETM = DATETINE ( ) and timein the format yyyymmdchtrnestt. Tho years four igs and incest cent. Hint Its good practice to se parentheses for buin functions, even when thee are no arguments, This ensures an unambiguous reference to a function rather than a variable. ‘The DATE, TIME, and DATETIME functions are examples of the few PL/" ouil-in functions that do not have arguments. These functions retum the current date an time, DDATE retus the curent dale as a character sting in the formal yy, The formats independent of the dale standard used in your county. For examle, 090131" relumedif the dale is Janvary 31, 2008, Hee Buin Funeions> Date ané Tne CAC™ACI Cac Example 1 DATE Dee) ‘Value assigned to TODAY i the curent date TODAY = DATE ( )j-¢ inte frat ym (ear rent ay. The year's two digs ard exes te century. ____————————— Example 2 TIME DCLCTIME CHAR (9); | Value assigned to CTIME isthe current CTIME = TIME ( );-¢—— nein fara hess ous, minutes, seconds, millseconcs) ee st ]SY Example 3 DATETIME SN ‘Vale esiged to CDATETVis the cure cle COATETM = DATETIE ( );-¢——ndtine inthe frat yma The years fur digs and incutes he cent. —$£$_ $a Hint: It is good practice to use parentheses for buil-n functions, even when there are no arguments. ‘This ensures an unambiguous reference to a function rather than a variable. ‘The TIME function retums the curenttime as a characler string in hhmmsstt format. The houris in 24-hour format, for example, 72530000’ represents 05:25:30 PM. The DATETIME functions combines the DATE and TIME functions, and retums both the curent date and ime in a characer sting, For the date and time used above, the sting value '20080131172520000" would be returned, This function has the advantage of retrieving both date and time values with a single statement, and it returns @ four-digit year in the date, Coe) |VARC = MODIVARA.VARB]; The amet bitin uncon MODis used forebn he reinderhais et afr cing VARA by VARB. Exit “Type te code fra statement using @PLI bull function that ould be used to assign the remainder resting ftom dvdng VARA by \VARB to vale VARC. DCL VARA FIXED DEC(11), VARB FIXED DEC(5), VARC FIXED DEC(7); VARA = 47252; VARB = 11; ARC = 2 ‘lick Check My Answer to compare your answer with the suggested solution ae QQ check my Answer ff Aray Handling Fur Example 1 LBOUND and HOUND General format: UBOUND (array identifier , dimension ) HBOUND (array identifier , dimension ) DCL ARRL. = (O:4, 2) FIXED DEC (9,2) INIT ( (8)0 ); DCL (1,) ) FIXED BIN (15); LBOUND retums the value 0, HEOUND retums the value 4 These ate the lover and DO I = LBOUND (ARR1, 1) TO HBOUND (ARRL, 1) Grom toate ester ct AE TO ¥800N0 (ARRL, 2); Hs UNDretumsihe va 2, upper bound ote scan denson of ARR, ‘The LBOUND and HBOUND functions are used when processing arrays. LBOUND retuns the lower bound of the selected array dimension and HBOUND returns the upper bound. ‘As shown inthe above example, these ae generally used in lace of ileger contents where ara bounds re nomally coded, such as for doloops. Using hese funeons ensures that your code wil not have tobe changed if aray extens are alered Tok Datatrain Sut Foci Ary ang uncon acoA ccac General format: SUM (array reference ) DCL —ARR2(3,2) FIXED DEC (3) INIT ( 3,6,4,7,5,9 J; DCL TOTVAL «FIXED DEC (5); The value assigned to TOTVAL is 34 - the sum of alte values in array ARR2. . The value assigned to TOTVAL is 9-the sum TOTVAL = Sum (ARR2 (1,*) )} Torte vals in aRR0(1 ard ARR. TOTVAL = SUM (ARR2 (*,*) ); <——J The SUM function is used to calcula the total of values in an arithmetic array, or a cross-section of the array, The value returned is the sum otal re values the spected aay laments, ‘The above examples show how an entire array and a cross-section of an array can be used with the SUM function, Refer to the PL Language Reference Manual or nformation about other PL aray handing functions. Page 190f30 [O}(0) Introduction to Files File stored on adevce, | > = ‘ peter estrtae data transmission bi A) > Disk File butfer in memory Record-onlented PLit file processing. Field | Field2 | Field 3 Logical records accessed by a PL program. The ability to read or write data to external devices, such as disk files, tape, or printers, is an important aspect of programming, Files are stored on physical devices, suchas sks or tapes. A fle or dataset holds a colecton of information thats logical elated, such as a lent Master File or a Monthly Invoice Fils. Each logical recordin a file holds the data relating to ane occurence of the information, such as one client or one invoice. In turn, each record oontains one or more Gala fields thal represent each ofthe segments of data for thal record Typical elds ina et Mase File record are cent ame, cent adress, and lant account number. These fils appear in every record, Records canals be grouped int a physical block thal is sed to tens dl oad roma file fatatrain Fie stored ona dvi, ¢ ch erage | data transmission | vd Disk Index Y Glossary Y Help Print File buffer in memory Recond-orented PLi fle processing. Field1 | Field 2 Field 3 Logical records accessed by a PLIT program. Logica reo and fll ae the unis of fle information that ae normaly rocessc ina PL program. The statements used to ope, ‘close, and process files are collectively called record-oriented data transmission statements. This module will show you haw to use these statements fo process sequental fies. ‘Another less frequenty-used method of PL fle prooessing i called srearriented data transmission, which s covered later in this ‘course. Laveen \ Important characteristics of PLI1 consecutive file processit Records can be fixed or varying length Records can be blocked or unblocked. Resords can only be read sequentially Records can be added to the end o he fle only. Records can be updated in place, bu cannot be deleted. Files stored on a tape or cartridge use this file type. Sequential fies are used in PL/ programs when records are to be read, witlen, and undated consecutvely. The records are aways reteved in the order in which they were orignal inserted The ote’ filetypes that are processed in PL/t are REGIONAL, INDEXED, and VSAM data sets. In this module, you wil focus on the PLM statements that are used lo process sequential files. es fac acc ac General syntax of the DECLARE statement for a fle being processed using PL/1 record oriented transmission: | ‘The FILE attribute spectes that | | The RECORD attribute means daa is processed this data tem refers to fle. | [inthe program via logical records. y oa Filename FILE RECORD [function] [access] [buffering] 4 [ENVERONWENT (option Tist)] [KEvED]; Lgl fle name used asthe identie for fle processing ttements coded in your program. Examples: DCL TAPEIN FILE RECORD INPUT SEQUENTIAL; DCL DISKOUT FILE RECORD OUTPUT SEQUENTIAL; Note: There are other attributes that can be assoclated with a file, bbut these are outside the scope of the current course. There must be @ fle declaration statement fr each file that you use in your PLY program. The DECLARE statement fora fle has a ‘umber of new atrbutes that define the typeof file thatitis, and how the fle isto be used inthe program Thee names the agial denier tha you use ta reference the le This rare shuld ime to a maximum length of seven byles {or 2NSE or ight byls for 10S, You vl so how this le nae assole le references in your program wth he external datas Note that there are some variations in syrax between IBM 2/08 and 2VSE operating systems when dering and using fes in PL/ These ciferences wil be noted where appcebe. [EEN Pex Ycosny wo \ rit ext | The function attribute specifies the type of fle avy. can be INPUT, OUTPUT, or UPDATE, The access atte species haw the records in the ile are to be accessed. Itcan be | SEQUENTIAL, DIRECT, or TRANSIENT. v FILE RECORD [function] [access] [buffering] oa = Filenane [ENVIRONMENT (option Tist)] [kEVED]; The buffering abut sreifes whether intermedi storage burs are tobe used. Itcan be BUFFERED or UNBUFFERED, Examples: DCL TRANS FILE RECORD; (default INPUT SEQL) oc. ACCUAST FILE RECORD UPDATE; (default SEQL) Inthis module, you will ook at consecutive fle access for INPUT, OUTPUT, and UPDATE function processing. Note the following defaults: ~ INPUT is the default function fle attribute, if omitted ~ SEQUENTIAL or SEQL is the default access file attibute ~ The buffering attribute is normally omitted and defaults to BUFFERED or BUF for sequential fle processing ‘Youwil look at direct fe access and the KEYED attribute in another module. Datatrai Cred ‘Consecutive File Proce Wein Index Y Glossary {Help {Print exit filenane FILE RECORD [function] [access] [buffering] [ENVIROWENT (option Tist)] [KevED]; Some ENVIRONMENT options commonly used for non-VSAM consecutive fle processing Examples: Record format; F (xed unblocked), FB [ned blocked) \ (variable unblocked), VB (variable blocked) U (undefined) etc. RECSIZE (rn) (logical record size in bytes) BLKSIZE (nn) (physical block size in bytes) MEDIUM (SYSnnn) (gical unt -z/VSE onl) BUFFERS (n) (numberof burs) Printer Control: CTLASA or CTL360_ (carriage control character sel) Hint: The ENVIRONMENT keyword can be abbreviated o ENV. The ENVIRONMENT fe atirbute can be used to provide the physical characteristics of fl. There are many opton fr this atriute, some af which are shown above, Refer lo te PL manuals applicable fo your operating sysem or afullis of opis and their usage. Note that options inthe ENV option isl ae separated by oe or more spaces, er @ comma, DEC Datatrai CE cdis ET eer td Exit Examples | DCL TNWAST-— FILE RECORD. UPDATE ENV (FB RECSIZE(150) BLKSIZE(15000) ); DCL DLYTRAN «FILE RECORD. INPUT. EDIUM option used inthe ENV (FB, RECSIZE(40), BLKSIZE(4000) , LAVSE operating system ony. MEDIUM(SYS07), BUFFERS(2) ); DCL REPORT FILE RECORD OUTPUT ENV (F RECSIZE(133) CTLASA ); Forthe 2VSE operating syste, fle speccatons such a record forma, rear siz, and block size ae generally provide in the ENV atin; however, for210S, these specfcatons are more fen provided on the fle DD statement in he JCL, making the program independent ol the physical fle characterises. ‘You willlook at some acdtional ENV options for VSAM fles and othe cirecl access fle types in another module Datatrain WEE ing > Explicity Opening Files TACT AC EM, Basic syntax ofthe OPEN statement: Rane isd nie le DECLARE stent OPEN FILE (Fileref)— [INPUT | OUTPUT | UPDATE] [rite (Filenane2)] | rar sig nig [other file attributes] ; Ent fle alles rl ready coded an te ie DECLARE saenen. Examples OPEN FILE (TRANIN); OPEN FILE (TRANIN), FILE (LEDGER); ‘Mutiple es can be opened witha single OPEN staternent, Before afl canbe used by a program, it must be associate witha dataset. Opening a fle creates that association and imvokes a rnge of operating sytem suppor. You can enplcily pen one or mare fies by using the OPEN statement. The fileref used in the OPEN statement the same asthe filename used inthe fie delaraion. Ths denier also refers tote le ame used the JCL thal runs your progam. The TITLE option enables you to refer to an alternative le name inthe JC, i required. If an OPEN statement isnot executed fora le, the fle is opened implcty by the execution ofthe fst UO statement for that fe. Options and attributes thal are coded on the fle declaration can be augmented by adding options and atributes tothe OPEN statement When file prosessing is completed, the fle should be closed to cissociate the fie from the dataset. This is performed witn a CLOSE FILE(filef) statement i [ Defining Co i [BCL FILEOUT FILE RECORD OUTPUT SEQL ENV| FB, RECSIZE(8), BLKSIZE(27820) {Commasin the ENV atti fist ae opal. The SEQL attribute is the cefut and could have been cited Noe that forthe 2SE loperating system, you would have to code an extra ENV atibule forthe logical unt, for example, MEDIUM(SYSO09), ‘Type the code to complete the missing atirbutes on this file declaration to specify the following characteistes: -Fileisa new sequential ouput fle - Recor formats fixed blocked - Record size is 80 bytes Block size 27920 bytes OCL FILEOUT FILE RECORD _ eu ) Click Check My Answer to compare your answer with the suggested solution, Q Qf check my Answer ff Physical File A Ts aes er [iO >. (Filename 0D... (2/05) lnput Jf OBL filename... (2/vst)|}¢——— J/ TLBL Filename ... (2/VSE) > Output — Update Physical data set Logica fle name “OPEN FILE (FILEIN); OPEN FILE (WRKFILE) OUTPUT TITLE (‘TEMPFL'); \When a lis opene, the operating system eslabishes alin between the lgjical fein your program and the pyscal dataset. The fileref used in the OPEN statement is matched! to data set definition statement in the JCL. In turn, this defines the external device and optional physical characteristics forthe dala set. The TITLE onan is only required when you want fo use a name ther than flere in he CL. inthe above example, WRKFILE is the name ofthe fle used inte program, but TEMPFL she fle name dfn inthe ICL Da Pe ae > Input FaCCacac Examples of record I/O area declarations: Fe 0 area ora ck. RECAREA CHAR (40); ‘and ung logical a DCL 1 RECTYPEA BASED (ADDR (RECAREA) ), FIELDL CHAR (5), FIELD2 HAR (25), FIELDS HAR (10) ; Refning RECAREA process tociering record ayuts DCL 1 -RECTYPEB BASED (ADDR (RECAREA) ), FIELD4 CHAR (28), FIELDS FIXED DEC (9,2), FIELD6 HAR (15); DCL 1 RECSTRUC, 3 FIELD? can (10), 3° FIELD8 FIXED DEC (11,2), | Structures can be used as fe 10 areas to| 3 FIeLD9 alr (8), access each eld wt he logical recor 3° FIELOLB Pic '(5)9", 3 FIELOLL HAR (18); ‘When you read or write data to a file in PL, the data is processed in your program by using logical records. You must declare data variadles or structures to hold these logical records and aocess individual is, Each record area must be large enough to store one record. Inthe above example for RECAREA, the record size for he fle must not exceed 40 byes, Variables or structure that are used as record IO areas in PL/t are not exclusive to any one file, but its good practice to declare separate areas for each fle used. Datatrain Me |_ Examples of record 10 area declaration: ) oa RECAREA CHAR (4) 5; and ing gil eas, OCL 1 RECTYPEA ——_—BASED (ADDR (RECAREA) ), 3 FreLDL HAR (5), 3 FreLo2 CHAR (25), 3 FIELD} CHAR (16); Redefining RECAREA process 0 differing record layouts, DCL 1 RECTYPEB ——_—BASED (ADDR (RECAREA) ), 3 FreLDt CHAR (22), 3 FIELDS FINED DEC (9,2), 3 FIELD CHAR (15); oc 1 RECSTRUC, 3 FIELD? cHaR (10) , 3 FIELDS FIXED DEC (11,2), | Structures can be used as fle lO areas to 3 Freud arr (8), access each eld tin he logical cad, 3 FIELDIO PIC '(5)9", 3 FIELDIL HAR (18); Stucurs are a useful way of dering and accessing al the elds contained in each recor however, PL does nt validate the fomat ofeach eld when transiting deta using recort-orented processing. For example, FIELDS in RECSTRUL is nt checked for avalé decimal xed point vaive when reading or wring records. When a fie contains mare than ane type of record, the different layouts can be defined, es shown in the RECTYPEA and RECTYPEB structures. Bath of these overlay @ common VO area. You will now see how records are read into and written from these fle WO areas. Datatrain Consecutive File Processing > Rea TSS Tex Y issny tap (Pt Ba Reading lhe records nfl sequerilly, DCL FILEIN FILE RECORD INPUT EW (FB, RECSIZE (50), BLKSIZE (5000) ) cL EOF BIT (1) STATIC INIT('O'8); ba 1 PREC, Input struct used as 10 area, 3 Ful cian (3e), ees 3 FLO2 CHAR (5), 3 FLD3 CHAR (15); ON ENDFILE (FILEIN) EOF = ‘1'8; | See end-ofile concition later inthis module, OPEN FILE (FILEIN); pi Reads the frst egal record fom READ FILE (FILEIN) INTO (INPREC) ; FILENN into the INPREC stucure. DO WHILE (7EOF); Statements to process each record . _ Reads the net logical recor tom READ FILE (FILEIN) INTO (INPREC); PLEWinis th REREC shuctr. ‘The Pt READ statement is usad to read record from a fe, The basi syntaxis: READ FILE(F) INTO(r); Inthe above example, te frst READ statement wil retive he fil oil reo from FLEIN. Each subsequent READ statement thal is executed wil rtreve the next logical record uni all cerds have been red, Typically, tis is done by using a 00 WHILE lop, as shawn. The dala for each recor is placed in the structure INPREC so tat incu ld values canbe used. Late you wil see howto contol what happens afer th lest record is read rein Coe Cg cutive File Processing > Creating a New Cons | ‘Writing records sequentially to a new consecutive file: bck. FILEOUT oc. oad oc. OPEN FILE (FILEOUT); pp dO WHILE (I< 10); T=1+] Statenents to build output record FILE RECORD OUTPUT y | Logica record size. ENV ( FB, RECSIZE (40), BLKSIZE (400) )} | Output area for FILE ouput, OUTREC HAR (48); —| pach mustbe exact 40 bls. RECA BASED (ADDR (QUTREC) ), FLDL CHAR (10), FLOZ FIXED DEC (11,2), FLD3 CHAR (24); I FIXED BIN (15) INIT(O); Writes each aia recor toe WRITE FILE (FILEOUT) FROM (OUTREC); FILEQUT from the OUTREC variable, Note: For ied length records, he ouput record area must be eval the same lenglhas the record size. ‘The PLI1 WRITE statamentis used to write records toa fle, The basi syntax is: WRITE FILE(#) FROM(r); In the above example, ten records are writen sequentaly tothe ouput fle FILEOUT in a DO WHILE loop. The data for each record ould be assigned tothe RECA stucture elements FLD, FLD2, and FLDS inthe loop before each WRITE statement is executed. Because QUTREC and RECA refer to the same area of storage, you could also write the records from RECA with the statement: WRITE FILE(FILEGUT) —_FROM(RECA) ; Leary ay Cee daes Updating an Existing C LAC ACAGC ACG) |_ Updating reads pace in a consecutive fe: oe. FILEUPD FILE RECORD UPDATE ENV ( FB, RECSIZE (50), BLKSIZE (5000) ); pat OF srr (1) STATIC INIT(‘O'B); oe. UPDATENEEDED —BIT(1) STATIC INIT('9'8); | —————__—__ ran leer Stueture used 2s 10 area for + both reading and wang records. 3 FDL cian (30), ——————— 3 FLDZ CHAR (5), 3 FLD3 CHAR (15); (ON ENDFILE (FILEUPD) OF = '1'8; | Se end-ffe contin later his mul OPEN FILE (FILEUPD); Reads the rt gical record ra pP READ FILE (FILEUPD) INTO (UPDREC); FILEUPD into the UPOREC stucure. 00 WHILE (>E0F); Statenents to update selected records ‘TF UPDATE_NEEDED Tom GuiU eA . tes the curent record to ‘THEN REWRITE FILE (FILEUPD) FROM (UPOREC);—|+ 7 he UPDREC siuctre. READ FILE (FILEUPD) INTO (UPDREC); 110; Reads the next logical record ftom FILEUPD into the UPOREC structure. ‘The REWRITE statements used to update records ona fle ts valid only on flas declared withthe UPDATE attribute, The basic syntax for this statements: REWRITE FILE(S) FROM (r): In the above example, the READ stalementis used to retrieve each consecutive record from te file FILEUPD. Same or alo the records. ate then updated vith the loop by assigning new values to one or more of te felcsin the structure UPDREC. Pra @ Marten CorseciveFlePocessng> Unig anBicinCrecinehle CAC TA CE | Updating record in lace on a sequential fie: ba FILEUPO FILE RECORD UPDATE ENV ( FB, RECSIZE (50), BLKSIZE (S000) ); DcL EOF BIT (1) STATIC INIT(‘A'B); ba UPDATE NEEDED sIT(1) STATIC INIT('0"B); truce used as UO ta for be 1 UPDREC, | tr eaing and wring record 3 FLDL CHAR (30), 3 FLD2 CHAR (5), FLD3 CHAR (15); ON ENDFILE (FILEUPO) EOF i | See ene canton tater in tis mou. OPEN FILE (FILEUPO); READ FILE (FILEUPD) INTO (UPDREC); ———————| Se cee DO WHILE (EOF); - Statements to update selected records ... IF UPDATE_NEEDED THEN REWRITE FILE (FILEUPO) FROM (uPoaec) ; —| fowls corn eco eFLEUPD READ FILE (FILEUPD) INTO (UPDREC); 0; Reads the next logical record from FILEUPO ino the UPOREC structure. Each rend then updated in place by using a REWRITE sltement You do ot have lo revi ever ecard ihatis ead because the ‘records that you want to update can be selected. Records that are not rewritten remain unchanged on the fil. Note thal tape or cartdge fies cannot be updated in pace. For these datasets, you must read all he record from the old ie, and write records to a newfie Pooks Index Y Glossary Help Print Y Ex JREAD FILE(TRANS} INTO(TRANREC|: JWRITE FILE(MAST) FROMNASTREC): |TRANREC and MASTREC canbe decaredas element variables for stucsures witha total ength equal othe gical record length of leach fl. Type the code forthe statement required to read the next logical record from input fle TRANS and place itinanint ‘area called ‘TRANREG, and als forth satement required to add a new record oa conscutve ouput fle MAST using an ouput area caled MASTREC. Click Check My Answer c compare your ans wit the suggested solution, Q Qf check hy Answer ff 4 Nest Y Consecutive File Processing > End-of File cL. FILEIN Del. EOF jm ON ENDFILE (FILEIN) OPEN FILE (FILEIA); DO WHILE (sE0F); READ statement raises the ENDFILE condition which “— passes contol othe ON-nit, | — READ END} Handing the ENDFILE(end-tfie) condi EoF = '1'B; — READ FILE (FILEIN) INTO (INPREC); Statements to process each record .... Next. statenent Index Giossary \ Help Print FILE RECORD INPUT; BIT (1) STATIC INIT('9'B); JENDFILE ON-nitis executed and contro then retus lo te net statement ale the READ statement, IN) INTO (INPREC); — ‘When reading records sequentially from a file, PL will signal that the end ofthe file has been reached when a READ statement is processed, and the last record has already been read. \When this happens, PL triggers condition called ENDFILE, and controls passed to special black called an ON-unit, QQ Exit ec aie acc ie Index Glossary Help “Print exit Handling the ENDFILE (end-of-fle) condition: Dc. = FILEIN FILE RECORD INPUT; pc. EOF ait (1) STATIC INIT('o'); ENDFILE ON unitis executed and conto then retums EE tote nel slteenl al tle READ semen. OPEN FILE (FILEIN); READ FILE (FILEIN) INTO (INPREC); DO WHILE (EOF); ‘Statements to process each record .... READ statement rises the IENOFILE condition which passes cant othe ON-unit | SAD FILE (FILEIN) INTO (NPI Next statement END; The above example ilusraes a common method for handing the ENDFILE condition. AIT sing variable named EOF is used to indcae when end-le has been reached fr fle FILEIN. ls valu is changed rom 0 (OFF) to" (ON) when the ENDFILE condition istiggered, ‘Aller the ENDFILE ON-unit has been processed, PL!" passes control back to the statement immediately folowing the READ stalement. The DO WHILE loop wil then be terminated on the next cycle because the EOF indicator now has a value of ''B. Datatrain fran! Ceci lic) Index Glossary \ Print Exit Basic syntax of the CLOSE statement: CLOSE FILE (Filenanel) [,FILE (Filenane2)....Jj Using the CLOSE statement: cL FILEIN FILE RECORD INPUT} cL FOF BIT (1) STATIC INIT("9'B); ( ENDFILE (FILEIN) EOF = '1'B; OPEN FILE (FILEIN); READ FILE (FILEIN) INTO CINPREC); DO WHILE (7EOF); Statenents to process each record .... READ FILE (FILEIN) INTO (INPREC); END; CLOSE FILE (FILEIN); | Closes th input fo FILEN air al records hve boen processed —_—}{2_ ————————_J ‘The CLOSE statement is used to complete any outstanding data transmission to the file from the buffers and close the file. You can also dose multiple files with ane CLOSE statement, for examole CLOSE FILE (FILA) FILE (FILB) Datatrain ogee BUC} [+Pevous J wea] ‘Consecutive File Processing > Implicit Open and Close Index Y Glossary Help X Print ext Example of implicit OPEN and CLOSE; ON ENDFILE (FILEIN) EOF = '1'B; READ FILE (FILEIN) INTO (INPREC); 00. WHILE ("E0F); Statenents to process each record .... READ FILE (FILEIN) INTO (INPREC); oy ifyou omit any OPEN or CLOSE statements fr les accessed in your program, PL wilimpkcity open or lose hase fies. leis imply opened just before te frst fle processing statements execute for tha file, for example, a READ or WRITE sllement. ‘ies imply closed when te program erinaesromally. tatrain Page230t34 EMO) Vete(O esMNuitela In this module, you looked at record-oriented fle processing andthe syntax ofthe PL statements that are used lo define, open, and close files. You ‘also examined the PL!’ statements that are used to ‘ead, write, and update consecutive fles. ‘You should now be atl to: + deity 2 Fl, Physic Block, Logeal Record, and Data Field = Code a DECLARE Statement for a Consecutive File = dently How to PL Statements to Open and Close Fies - Identfy How to Use PLI Statements to Read, White, and Update Consecutive Files Lerten Exit Ge} Wied (ue aal Ma cele o: BM Vals to: December 31,2018 IF YOU D0 NOT AGREE WITH THESE TERNS AND CONDITIONS, DONOT CONTE WTHTHE USE OFT [I] SOFTWARE. El IMPORTANT: DATATASK PTY LD, IS BUSINESS PARTNERS, AND IT AUTHORZED DISTRIBUTORS (te Licensor) ARE WLLING TO LICENSE DATATRANN the Sttwat) TO YOU ONLY ON THE CONDITION THAT YOU ACCEPT THE ‘TERMS AND CONDITIONS CONTAINED IN THS LICENSE AGREEUENT AND BY USING THE SOFTWARE YOU AGREE TO BE BOUND BY ALL OF THE TERNS AND CONOTTONS OF THS LICENSE AGREEWENT.F YOU DO NOT AGREE TO THE SEMRE TERNS THE CEU 8 TOLIAEURE THE SMETWARE TA lM siow EvENT vouiMay [Y] a foc Fer Xcessay top Y rine Yen (ote Re oy rele In this module, you will discover how to use record keys to del access eco in a dl sel, and how to process keyed fles randomly and sequenily. You wil loo al LOCATE mode fo processing, and ‘see how to process records in system allocated fle wes. ‘After completing this module, you will be able to: - Recognize he Keyed Fe Types Used in PLit ~ Code PL! Statements to Read, Wrle, Delete, and Uneiate Records Direc By Using Keys + Identfy How to Handle the Pit KEY Condition When a Record Is Not Found ~ Use READ and LOCATE Statements to Process Records in a Fle Buffer ry a Access File Processing X p Record 2 Danse leetreacs [~[~ Record 3 Record 1 ‘You have seen how to code PLi statements to process consecutive files and now you wil ook atthe other fle types that can be acoessed by using recard-orented fle processing, This module wil explore the extensions tothe syntax of PL fle dfinton, and I/O statements used to process VSAM, REGIONAL, and INDEXED fle types. ‘This module isan introduction to random aocess files. Refer tothe relevant PL manuals for more information abou fle processing. Page Direet Access File Processing > Keys and Random Record Access Index T clessary Help T Exit CONSECUTIVE | Sequential fatfie | Sequential aovess only REGIONAL Direct access Random and sequential access INDEXED Key-sequenced Rendom and sequential acoess VSAMRRDS | Relative record Random and sequential aooess VSAMESDS | Enity sequenced Random and sequential aooess ‘VSAM KSDS Key-sequenced Random and sequential access Fles can be processed sequentaly by reading, wring, or updating records inthe orderin which they are store onthe fl, but this meth ole processing is ot alvays the mos efcent, particularly when only smal perceniage of the records onthe fle re ta be accessed. To overcome this problem, a range of le types tat use record keys to uniquely deni each records avaiable, These keys are used to ‘rectly access individual records in your program witnout having to read the entire fle PL/1 can use VSAM, REGIONAL, and INDEXED fle types or his purpose. [tetoeti Ko File types: CONSECUTIVE REGIONAL INDEXED VSAM RRDS VSAM ESDS ‘VSAM KSDS ened Sequential lat fle Direct access Key-sequenced Relative record Entry sequenced Koy sequenced Yio (ns ie Fan m Sequential acoess only Random and sequential access Random and sequential access Random and sequertia access Random and sequential access Random and sequential access \VSAM dat sts are the most commonly used dala setsin ¢ commercial IBM environment. REGIONAL datasets are general used only {or special purposes when mae conto required verte physical organization of records ana fle, INDEXED data sels usualy appear cniyin legacy mairrame systems, orn pltiorms other than BM Datatrain eed SAN KSDS Date LAC ACI Gx Primary ndex uses the Account Nurberfeki | tema or secondary nde using the whichis par othe recard and must be unique. | | Surame el, utch canbe non-niqu. i There ae three types of VSAM fle organization The st is @ VSAM keysequenced dataset KSDS). Each record inthis le type is ideniid by 2 unique primary key. The Keys erbedced inthe data foreach record andi ls sored ina separale index fle, whichis used ta aoness each record dient oro process the records in key sequence. |VSAM KSDS dala sts can alsa have one or more altemate inc that enable you to acoess te records by using a Key oer han the primary key. The SURNAME field inthe above table is an example of an alternate index. Keys in altemateincioes do nat have tobe unique. Oc Lay Direct 508 bases ATACT ACI AGR, Basic syntax of the declaration for a VSAM KSDS file: | QUTPUT onl valid on KSDS fle when KEYED atirbuts is aso used or imp. DCL MYKSDS FILE RECORD [INPUT | OUTPUT | UPDATE] pple] prrecr | seat] a The KEVED atibule indicates thatrecord] ENV ( YSAMy «++ i | [Records are processed randomly via the keys canbe used in yur pteoram uhen |x or seecndary keys. The RECT racing, wring, or dling recs. atte alas implies he KEYED atu Indicates isis VSAM le ype ‘swith al native VSAM files, you do not have o spect the charecerstis o he fein the fle declaration, such as record length or record format. ‘These characteristics are defined to VSAM itself when the external dataset is defined, and are not required in your program. The only ‘mandatory atbute used to identify ary VSAM fle in PL isthe ENV(VSAM) atrioute, as shawn inthe above example, Other ENV options ean be used to spect diferent types of fie processing, as we shall see later ‘Access File Processing » Declaring VSAM KSDS Data Set Peer cssay Y top Y rine Yen Examples: SDS used tonal oad records toa new data se; reoords must be added in primary Key sequence Dc. KSDSOUT FILE RECORD OUTPUT KEYED SEQL ENV(VSAM); SDS used to access records in ascending prey or alternate key sequence: DCL KSDSINE FILE RECORD INPUT KEYED SEQL ENV(VSAM); KSDS used to process records directly. Individual records can be read, added, updated, or deleted, using the record key. DCL — KSDSUPD FILE RECORD UPDATE KEYED DIRECT ENV(VSA); Ifyou code the DIRECT attribute, dial record canbe recy read, acd, undated, and deleted by using a spetic record key. SEOL means that recor are processed sequential in ascencing or descending key sequence By using the KEYED and SEQL atribues together, you can skip to ferent key locations in he let sla sequential access. Thisis non as skip sequential processing. Later i his mocule, you wil se how both dec and sequential VSAM fle processing is performed in PLM. ory Peedi Pimaryindexs the REA, hich is maitsins by VSAM ands nl pat f the record. Peed Index Glossary Help print ex Alternate index using the Date field, ich canbe a non-niaue ey. ! Trans number 6836940 2975296 AVSAM enty sequenced dataset (ESDS)is primary a sequent fe orgarizaton wher each ects identi bis lave bye address (RBA), The RBA indicates the offset of the record within the entire fie, starting with an offset of zero for the first record. Unlike SDS datasets, the RBA key isnot part of the data record and isnot used for dey accessing inca ecards, These fs can aso be accassed trough an allem index, which can have unique or norunique Keys. Cree Direct A + Fl Pres Deg EAM ESD Ses Fact cac FILE RECORD [INPUT | OUTPUT | UPDATE] (keveo] —[orrect | seq] ENV (VSAM es )5 ESDS used to load or append records to a dataset; SDS used to read records sequently in the order they were loaded: SDS used to read records direct via analterate index wih unigue keys: \VSAM ESDS fles are most commonly use ke standard sequential fles. The KEYED atrbute is rarely used to access records using the primary RBA ke, but canbe used when te leis being processed through an alta index. When an ESDS dala sels processed sequently, reords ae reieved inthe order in which they were added, Records canbe updated inplace oragoended to the end ofthe fi, bu records cannot be inserted nthe mide of the le. Da Pea To] ioe (Oni indexis the RRN, which ‘Snot part the record. | AVSAM relative record data set (RRDS) is an indexed data sel where each record is identified by is relative record number (RN). The RRN isan eighi-gi number stating with 00000001 forthe fst record, which incicates te relative poston of the record within the entre fle ecards canbe reiaved sequential in ecard number sequence, or accessed ret by using the RRN asthe key. Any unused record rumbers arena tured when te fl is read sequently or drect. A VSAM RROS cannot have altate indices. cer Datatrain Pee ee Exit DCL -MYRRDS FILE RECORD [INPUT | OUTPUT | UPDATE] [weveo] [DIRECT | SEQL] ENV ( VSAM ); RROS used to randomly load records into a new dataset using the RRN Key: DCL —RROSOUT FILE RECORD OUTPUT KEYED DIRECT ENV(VSAM) | RRS used to read records in Relative Record Number sequence: DCL —-RRDSIN FILE RECORD INPUT KEYED SEQL ENV(VSAM); RRDS used to update reords direc via the RRN key: | DCL —RRDSUPD FILE RECORD UPDATE KEYED DIRECT ENV(VSAM) ; VSAM RRDS ies are general used when the primary access rough the record numer andthe total number of rear is eatively small. The processing options fortis typeof le are similar toa KSDS except there only oe key, which is predefined. Records cn be inserted sequential or crcl inta any unused record number slats in the fe, Records can also be undated in pace and dalted Caron The eion numbers not part ofthe datarecod. Dury records created inurosed regs, AREGIONAL({) data setis a direct access file where the records are placed in slots or regions. Each record occupies @ unique region and canbe accessed drt by using the region number as he key. Ths aso delerines the postion ofthe recordin the fie “The region number is an eight- Inial Loading ofa Keyed Data Set |_ Ii oacing ofa Keyed dataset oc. FILE0UT FILE RECORD OUTPUT <——— ht be vsed when oaing PAYED SEQ ENV(VSAH) records toa ne fie. stevie xEvamworkevTo | options ar used on he WRITE statement Must be wed whl acing 2 VSAN, efoing this DECLARE stale, SDS, ESDS, or INDENED dataset DCL RDATA (5) CHAR(20) STATIC INIT ( ‘Record pata 1', ‘Record pata 2', ‘Record Data 3", ‘Record Data 4’, "Record Data 5' ); DCL RN cHAR (8); mt DED BTN (D5 (ss aen readin FILED rd te OPEN FILE (FILEOUT)s rll recs rumber fe rearsin vate RN, bo T=1105; v WRITE FILE (FILEOUT) FROM (RDATA(I)) KEYTO (RRN); END; ‘The PL! WRITE statement can also be extended to load or insert records ino a keyed dataset. The basic syntax is WRITE FILE(file) FROH(rec) [ KEYFROM (keyval) | KEYTO (keyarea) J; When loeing a naw Hey dala sel, the fl isormally dered withthe SEOUL alibute, and records ae inset in ascending Key ‘sequence. For cartain data set types with non-embedded keys, such as VSAM RRDS or REGIONAL data sels, records can also be loaded randonly by using the DIRECT atu. Direct Acces lle Processing > Ital Loading of a Keyed Data Set Index _Y Glossary Print Y Ex | Ital loading ofa keyed dataset DCL FILEOUT FILE RECORD OUTPUT ¢ | ust be used when loin PP AEVED SEQ ENV(VSAM) | records to anew fe, A ‘Must be used if the KEYFROM or KEYTO cons are used onthe WRITE staterent Nust be used while loading a VSAM, refering o his DECLARE statement 50S, ESDS, or INDEXED daa set DCL ROATA (5) CHAR(20) STATIC INIT ("Record Data 1’, ‘Record Data 2", ‘Record Data 3", ‘Record Data 4", ‘record vata 5" ); DeL RN CHAR (8); mot ROE Dy Inserts @ new recordin FILEOUT and places the OPEN FILE (FILEOUT); reltve record numberof the recordin vavsbe RRA bo r=1705; v WRITE FILE (FILEOUT) FROM (RDATA(I)) KEYTO (RRN); END; ‘The KEYFROM option is used fo provide the key ofthe record 1 be added. You must use this option for lading a new fief you declared the fle ith the OUTPUT DIRECT attoules, or you are loading a VSAM KSDS or INDEXED file, The KEYTO oplon enables you to retiave the key of the recor just inserted. It can be used to retum te assigned key when lading fles sequently. This coud be the region number, RBA, or RRN ofthe recor Datatrain Per Direct Access File Poe PB ading ofa Keyed Data Set { Initial aang of a keyed detaset DCL = FILEQUT | Must be used if the KEYFROM or KEYTO opens ae used onthe WRITE statement refering to hs DECLARE statement DCL = -RDATA DcL RN char (8); DCL I OPEN FILE (FILEQUT); do T=17105; END; FILE RECORD OUTPUT <—_| EVD SEQL ENV(VSAM); (5) GHAR(20) STATIC INIT ( "Record Data 1", "Record Data 2", FINED BIN (15); y WRITE FILE (FILEOUT) FROW (ROATACT)) KEYTO (RRND; "record Data 3', ‘Record Data 4", "Record Data 5" ); Inserts a new recordin FILEOUT and places the relative record numberof the recordin variable RN. Ifyou are loading records sequentially and co not want to access record keys, you can omit both the KEYFROM and KEYTO options, ‘and also omit the KEYED atrioute on the fle declaration. The above example shows haw to load @ VSAM RRDS cal set and use the KEYTO option to relieve the RRN of each record inserted, ‘Note thal the KEYFROM option must alvays be used to load data sats wih embedded Kays, such as VSAM KSDS and INDEXED dala sats, Teen ory ea eee ren Vl iviex X X Help Trin Y f Updating records using keys | DCL FILEUPD FILE RECORD. UPDATE | Must be used when updating records on an existing fle KEYED DIRECT ENV(VSAN); 4 Must be used fr de! keyed reading or uring of rcs Must be used ithe KEY, KEVFRO, or DcL 1 ——_UPOREC, 3 KEVFLD CHAR (7), KEYTO epfions ate used on any stalk, 3 Fup ‘CHAR (5), 3 FLD3 ‘CHAR (16); DCL —_-RECKEY aR (7); OPEN FILE (FILEUPD); RECKEY = ' 001050"; Reads a record ety fom FILEUPD READ FILE (FILEUPD) INTO CUPDREC) KEY (RECKEY);< | vsiglhe value n RECKEY as Ihe key Statements to update the record —eEE—EES ‘Updites the record on FILEUPD. Note that RECKEY REWRITE FILE (FILEUPD) FROM (UPOREC) KEY (RECKEY) ;-<¢~| 62n contain any valid record key and does nct have {obe the key ol the record jst read | Satements to buld a new recor Inserts @ new recordin FTLEUPD with ky specified by RECKEY. RECKEY = '0007025'; WRITE FILE (FILEUPD) FROM (UPDREC) KEYFRON (RECKEY); In adlion o updating records in place, the PLA REWRITE staement canbe extended to update any record dredly on a keyed dala sol. The basic syntax is: REWRITE FILE( File) FROM (ree) {HEY (keyval) ]; When updating an essing keyed fle declared with UPDATE DIRECT attributes, records to be changed are generally rea fist as shown inthe above example, but ths is not mandatory. Cer Updating Records By Using Keys Index Glossary \ Help ‘Print Exit f Updating records using keys | DCL FILEUPD FILE RECORD UPDATE ¢ | Must be used when updating records onan exiting fe. KE DIRECT wv); t Must be used for direct keyed reading or wtng of records. ust be used ifthe KEY, KEYFRON, or me | roe cur (7), KEYTO options are used on any statement, 3 Fup2 HAR (3), 3 FLD3 CHAR (16); DCL RECKEY CHAR (7); OPEN FILE (FILEUPD); FCKEY = ‘ooo050'; Reads a recnd direct fe FILEVPO READ FILE (FILEUPD) INTO (UPDREC) KEY (RECKEY); | sing Ihe value in RECKEY a the key. ‘Statements to update the record... = Updates the record on FILEUPD. Note that RECKEY REWRITE FILE (FILEUPD) FRON (UPOREC) KEY (RECKEY);-<~|Cé0 conan any valid record key and doesnot have to bethe key ofthe record used ‘Statements to build a new record .... Inseris a new regord in FILEUPD with key specified by RECKEY. RECKEY = "9007025; WRITE FILE (FILEUPD) FROM (UPDREC) KEYFROM (RECKEY) ;¢————— The KEY opon defines he ky fhe rece to be update, and must be supped ithe DIRECT le abut is used, ‘The WRITE statement can also be used to inset new records in a Keyed dataset. This time, the <=VFRON option is used to specify the key of the new record, For a VSAM ESDS dataset, records are appended to the end ofthe fe. i tia eerie Index Y Glossary Y Hep Y Exit __Upating records using keys DCL FILEUPD FILE RECORD. UPDATE + Mus be used when updating records on an extn fle KEYED DIRECT EXV(VSAY); S__J iste tected retin or aig ora Must be used ithe KEY, KEYFROM, or DcL 1 UPDREC, 3 KEYFLD. «AR (7), EYTO opins ae used on any statement. 3 FLb2 char (5), 3 FLD Har (16); DCL —_RECKEY Har (7); OPEN FILE (FILEUPO); RECKEY = "Q001050'; Reads record det fom FILEUPO| READ FILE (PILEUPD) INTO (UPDREC) KEY (RECKEY);-¢—————| sing the valve in RECKEY as the key. | Statements to update the record Updates the record on FILEUPD. Nolte that RECKEY | REWRITE FILE (FILEUPD) FROM (UPDREC) EY (RECKEY’);-¢~| an coniain ay valid record key and does not have tobe the key ofthe record jus read | ‘Statements to build @ new record... Inserts a new regord in FILEUPO with a key specified by RECKEY, RECKEY = "8007025"; WRITE FILE (FILEUPD) FROM (UPDREC) KEYFROM (RECKEY) By declaring @ keyed data set as UPDATE SEQL, you can update records in place by using the REWRITE statement in a similar way to CONSECUTIVE fies. In tis case, the KEY option is omitted ftom the REWRITE statement andthe record just read is undated The above example shows how to update an insert records on @ VSAM KSDS dataset. Refer othe PLI1 Programing Guide for inforaton about the rues for updating each type of date sel Dit Aces Fi Peeing Deg Reais LacmAcacac Deleting records ) DCL FILEUPD FILE RECORD UPDATE << Must be specified if the DELETE statement is KEYED DIRECT ENV ( VAN); _|Usedveleing ois DECLARE statement pe 1 UpoREC, 3 KEYFLD CHAR (7), 3 FLo2 CHAR (5), 3 FLD3 cHar (16); BCL RECKEY CHAR (7); OPEN FILE (FILEUPD); Reads a record drat rm FILEUPD, using he valu in RECKEY a the ey. RECKEY = '0001050"; READ FILE (FILEUPD) INTO (UPDREC) KEY (vecxe;¢—— DELETE FILE (FILEUPO) KEY (RECKEY); << — [oti te cr ih ey seid RECKEY. RECKEY = '0023440"; DELETE FILE (FILEUPD) KEY (RECKEY);-¢ | Records canbe deleted rect, uithout being read frst. The DELETE statement can be used lo delete records fom 2 keyed le and is valié only on fies declared withthe UPDATE atrbue The basic synax for this satomentis DELETE FILE(File) KEV (keyval) ; Fora fe dedared wih DIRECT UPDATE atrbuis, any record can be deleted dec by spectying the KEY option. ln his case, record do not need tobe ret fst tobe deleted. The KEY optan can be omited for certain SEQ. UPDATE tes wher the ecard being deleted is the record just read ENE Fage aster | EY} Poca lien Cui Index Y Glossary Hep Exit |_Deleting records DCL FILEUPD FILE RECORD UPDATE | Must be specified ifthe DELETE statements KEYED DIRECT ENV ( vgaw); [sed eleingto tis DECLARE stale, pad UPDREC, 3 KEVFLD cHaR (7), 3 FLD2 aur (5), 3 FLD} van (16); DCL RECKEY aur (7); OPEN FILE (FILEUPD); Reads a record directly from FILEUPD, using the value in RECKEY as the key. RECKEY = ‘0901050'; READ FILE (FILEUPD) INTO (UPOREC) KEY (vecxey) 4] DELETE FILE (FILEUPD) KEV (RECKEY); < [pases acre ey pected in RECKE, RECKEY = '0023440'; DELETE FILE (FILEUPD) KEY (RECKEY); < | Records canbe deleted directly, without being read fil Recor’ canatbe deleted om VSAM ESDS deta ses by using the DELETE satement. When a record is deleted ttm @ REGIONAL data sel, the record is cowerted toa cummy rear, The above exail shows hw the DELETE staleent canbe used ona VSAM KSDS to delete seeced reco rend by sing record keys. cei.

You might also like