Sunteți pe pagina 1din 159

COO3077151

CourantMathematicsand
ComputingLaboratory
U.S.DepartmentofEnergy

ThePL/IProgrammingLanguage
PaulAbrahams

ResearchandDevelopmentReport
PreparedunderContractEY76C023077
withtheOfficeofEnergyResearch
MathematicsandComputing
March1978

NewYorkUniversity

UNCLASSIFIED

CourantMathematicsandComputingLaboratory
NewYorkUniversity

MathematicsandComputingCOO3077151

THEPL/IPROGRAMMINGLANGUAGE

PaulAbrahams

March1978

U.S.DepartmentofEnergy
ContractEY76C023077

UNCLASSIFIED

ThisreportistoappearasanarticleonthePL/I
programminglanguageintheEncyclopediaofComputer
ScienceandTechnologypublishedbyMarcelDekker,Inc,

ii

TableofContents
INTRODUCTION..............................................................1
SyntacticConventions...................................................6
DATATYPES................................................................9
ArithmeticTypes........................................................9
StringTypes...........................................................11
PicturedTypes.........................................................13
Pointers,AreasandOffsets............................................19
Files..................................................................20
Labels.................................................................22
Entries................................................................23
Formats................................................................24
Arrays.................................................................25
Structures.............................................................26
DECLARATIONS.............................................................29
Manifest,Explicit,Contextual,andImplicitDeclarations..............29
DeclarationsofStatementNames........................................31
AttributeConsistencyandCompleteness.................................32
StandardandUserDefinedDefaults.....................................38
TheLIKEAttribute.....................................................41
EXPRESSIONS,TYPECONVERSION,ANDASSIGNMENT.............................43
PrefixandInfixExpressions...........................................45
BuiltinFunctions......................................................51
TypeConversion........................................................64
Promotion..............................................................68
TheAssignmentStatement...............................................69
STORAGETYPES............................................................72
StaticStorage.........................................................72
AutomaticStorage......................................................73
ControlledStorage.....................................................73
BasedStorage..........................................................74
TheReferOption.......................................................77
LefttoRightCorrespondence...........................................79
AllocationinAreas....................................................80
ParameterStorage......................................................81
DefinedStorage........................................................82
Alignment..............................................................84
Initialization.........................................................86
PROCEDURES,SCOPES,ANDENVIRONMENTS.....................................88
iii

TheRETURNStatement...................................................90
ArgumentsandParameters...............................................91
Options................................................................93
Recursion..............................................................94
TheGENERICAttribute..................................................95
BlocksandScopes......................................................96
InternalandExternalScope............................................99
EntryValuesandEnvironments.........................................100
ONUNITSANDONSTATEMENTS..............................................102
TheONStatement,REVERTStatement,andSIGNALStatement..............105
EnablementandDisablement............................................108
BuiltinFunctionsforONConditions...................................109
CategorizationoftheONConditions...................................110
OTHERSTATEMENTSAFFECTINGFLOWOFCONTROL..............................115
ConditionalStatements................................................115
TheDOStatement......................................................116
TheGOTOstatement....................................................119
TheSTOPStatementandtheNullStatement.............................121
FILESANDRECORDINPUTOUTPUT...........................................122
FileAttributes.......................................................122
FileOpeningandAttributeDetermination..............................123
FileClosing..........................................................127
OperationsonRecordFiles............................................127
STREAMINPUTOUTPUT.....................................................135
DataLists............................................................137
ListDirectedInputOutput............................................138
DataDirectedInputOutput............................................140
EditDirectedInputOutput............................................142
BIBLIOGRAPHY............................................................150
EDITORIALNOTES.....................................................NOTES1
Acknowledgement...................................................NOTES1
Errata............................................................NOTES1
AbouttheAuthor..................................................NOTES2

iv

INTRODUCTION
PL/Iisalargeandpowerfulmultipurposeprogramming
language.TheintentofthedesignersofPL/Iwastocreate
alanguagethatcouldbeusedinbusinessandinscientific
applications,aswellasinsystemsprogrammingapplications
suchaswritingoperatingsystems.Theoriginaldesignwas
developedin1963byacommitteeofpeopledrawnfromIBM
andfromSHARE,anIBMusergroup.Foralongtimetheonly
importantimplementationsofPL/IwerethosedevelopedbyIBM
onthe360and370computers,andtheimplementationonthe
GE645attheMULTICSProjectatMIT.However,duringthe
early1970'sanumberofotherimplementationsarose.The
implementationofPL/Ibyotherorganizationswasgivenimpetus
bythedevelopmentofanationalandinternationalstandard
forPL/IbyasubcommitteeoftheAmericanNationalStandards
Institute,inconjunctionwithasimilarsubcommitteeofthe
EuropeanComputerManufacturers'Association.
ThedefinitionofStandardPL/Iwasformallyreleased
latein1976,butthecontentofthestandardwaspubliclyknown
wellbeforethen.Thestandarditselfwaswritteninanovel
mannerasasetofalgorithms,expressedinhighlystylized
English,fortheoperationofahypotheticalPL/Imachine.
TheversionofPL/IdescribedinthisarticleisStandardPL/I.
ThedesignofPL/Idrewheavilyonthemajorlanguages
thatexistedin1963:Fortran,Cobol,andAlgol60.The
syntaxofPL/ImostresemblesthatofFortran,butwithout

Fortran'srigidrulesforprogramformatting.Thenotionof
blockstructurewastakenfromAlgol60,whilePL/Istructures
weretakenfromtherecorddescriptionsofCobol.However,a
greatmanyfeatureswereaddedtoPL/Ithathavenocounter
partinitsancestorlanguages.
AnexampleofaPL/Iprogramisgiveninfigure1.A
programiswrittenasasequenceofexternalprocedures,which
aredefinedinsuchawaythattheycanbecompiledseparately
andthenlinkedtogetherwhentheprogramisexecuted.Within
anexternalprocedure,therecanbeinternalprocedures.
Inthisexample,thereisoneinternalprocedure,named
GET_DIGRAM.Eachprocedureintheprogramconstitutesablock,
Inaddition,ablockcanbedelimitedbythePL/Istatements
BEGINandEND(asinAlgol60).
TheinternalprocedureGET_DIGRAMcommunicateswiththe
outerprocedureDIGRAMSviaargumentspassedtoGET_DIGRAM
bytheCALLstatement.FromtheviewpointofGET_DIGRAM,
theseargumentsappearasparametersandarelistedinthe
PROCEDUREstatement.
Thevariablesusedinthisprogramaregiveninthe
DECLAREstatements.Ingeneral,avariable(orotheruseof
anidentifier)isdescribedbyasetofattributes.Notall
oftheseneedbegivenintheDECLAREstatement;thosethat
arenotgivenarededucedthroughtheapplicationofasetof
defaultingrules.Infact,defaultingisappliedinagreat
manycontextswithinPL/I.

Onaccountofitscomprehensivenature,PL/Iisadiffi
cultlanguagetolearninitsentirety.Forthatreasonit
wasdesignedsothatausercouldlearnjustthosepartsof
thelanguagethatheneeded,andignoretherestofituntil
theoccasionarosetousesomepreviouslyuntriedfeature.
Theextensivedefaultingconventionswereincluded,fora
largepart,tomakeitpossibletowriteprogramswithout
havingtolearnaboutobscureandirrelevantattributes.For
instance,onecanwritebusinessprogramsinPL/Iwithout
everrealizingthatthelanguageincludescomplexnumbersand
anextensiverepertoireofmathematicalbuiltinfunctions.
SinceStandardPL/Iisintendedtobeimplementedona
varietyofmachines,thestandardprovidesthatanumberof
characteristicsofthelanguageareimplementationdefined.
Forexample,machinesdifferintheirwordlengths;therefore
themaximumnumberofdigitsthatneedbecarriedina
floatingpointcomputationisleftimplementeddefined.Inthe
descriptionofPL/Igiveninthisarticle,implementationdefined
featuresofthelanguagearereferredtofrequently.
Asofthiswriting,astandardsubsetversionofPL/I
isunderdevelopmentbytheAmericanNationalStandardsInsti
tute.Thedefinitionofthisstandardsubsetwillprobablybe
releasedbythetimethatthisarticleappears.Moreover,an
extensionofthesubsettoincludefacilitiesforrealtime
andconcurrentprogrammingisalsounderdevelopmentbythe
samegroup.

Figure1.ASamplePL/IProgram
/*

THISPROGRAMREADSINATEXTANDCOUNTSTHENUMBEROFTIMES
THATEACHALPHABETICDIGRAMOCCURS.ADIGRAMISASEQUENCE
OFTWOADJACENTCHARACTERS.FORINSTANCE,THEDIGRAMSIN
'GRUNGE"AREGR,RU,UN,NG,ANDGE.

*/
DIGRAMS:

PROCEDUREOPTIONS(MAIN);
DECLARECOUNT(26,26)FIXED(4);
/*COUNT(I,J)GIVESTHECURRENTCOUNTOFOCCURRENCES
OFTHEDIGRAMFORMEDFROMTHEITHLETTERAND
THEJTHLETTER.
*/
DECLAREALPHCHARACTER(26)INITIAL
('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
DECLARE(P1,P2)FIXED;/*ALPHABETICPOSITIONOFLETTER*/
DECLARE(L1,L2)CHARACTER(1);
/*FIRSTANDSECONDLETTERSOFDIGRAM*/
DECLAREDONEBIT(l)INITIAL('0'B);
/*COMPLETIONFLAG*/
/*SETALLELEMENTSOFTHECOUNTARRAYTOZERO*/
COUNT=0;
/*READANDPROCESSDIGRAMS*/
RDLOOP:
DOWHILE('1'B);
/*DOFOREVER*/
CALLGET_DIGRAM(L1,L2,D0NE);
IFDONETHEN
GOTOPRINT;
P1=INDEX(ALPH,L1);
P2=INDEX(ALPH,L2);
/*N.B.INDEXRETURNSZEROIFLETTERNOTINALPHABET*/
IFPI*P2>0THEN /*DIGRAMISALPHABETIC*/
C0UNT(P1,P2)=C0UNT(P1,P2)+1;
ENDRDLOOP;
/*PRINTTHERESULTS*/
PRINT:

DOP1=1TO26;
DOP2=1TO26;
IFCOUNT(P1,P2)>0THEN/*DIGRAMAPPEARED*/
PUTEDIT(SUBSTR(ALPH,P1,1),
SUBSTR(ALPH,P2,1),COUNT(P1,P2))
(SKIP,2A(l),X(2),F(4));
END;
END;
4

STOP;/*ENDEXECUTIONOFPROGRAM*/
Figure1.Continued
/*

INTERNALPROCEDURETOEXTRACTTHENEXTPAIR
FROMTHEINPUTTEXT

/*
GET_DIGRAM:

PROCEDURE(L1,L2,FLAG);
DECLARE(L1,L2)CHARACTER(1); /*LETTERPAIR*/
DECLAREFLAGBIT(l);
/*ENDOFDATAINDICATOR*/
DECLARECARDCHARACTER(80);
/*INPUTLINEIMAGE*/
DECLAREPOSNFIXEDSTATICINITIAL(80);
/*CHARACTERPOSITIONININPUT
CARD*/
DECLARESYSINRECORDINPUTFILE;
/*INPUTREADFROMFILESYSIN*/
ONENDFILE(SYSIN) /*WHENINPUTEXHAUSTED*/
GOTOINPUT_FINISHED;
IFPOSN>79THENDO;
READFILE(SYSIN)INTO(CARD); /*READACARD*/
POSN=1;
/*PROCESSFROMSTARTOFCARD*/
END;
L1=SUBSTR(CARD,POSN,1);
L2=SUBSTR(CARD,POSN+1,1);
POSN=POSN+1;
/*MOVETONEXTPAIR*/
RETURN;
/*EXITFROMTHISPROCEDURE*/

/*COMEHEREIFTHEREADSTATEMENTENCOUNTEREDANENDOFFILE*/
INPUT_FINISHED:
FLAG='1'B;
/*SIGNALCOMPLETIONTOCALLER*/
RETURN;
ENDGET_DIGRAM;
ENDDIGRAMS;

SyntacticConventions
APL/Iexternalprocedureconsistsofasequenceof
statements.WiththeexceptionsoftheIFstatementandthe
ONstatement,everystatementisfollowedbyasemicolon.
Theprogramispresentedinfreefieldformat,i.e.,statements
donotoccupyafixedpositionontheline.Infact,line
boundariesareignoredaltogether,soastatementcanbesplit
overseverallines,orseveralstatementscanoccupyasingle
line.Withtheexceptionoftheassignmentstatementandthe
nullstatement,thetypeofastatementisindicatedbythe
keywordwithwhichitbegins.
Astatement,inturn,iswrittenasasequenceoftokens
eachofwhichmaybeeitheradelimiteroranondelimiter.
Thetypesoftokensare:
Delimiters
operator

Nondelimiters
identifier

period

arithmeticconstant

comma

stringconstant

leftorrightparenthesis

isub[discussedbelow]

colon
semicolon
textinclusion
Twoadjacentnondelimitersmusthaveatleastoneblank
betweenthem,andotherthanthatadjacenttokensmayhave
anynumberofblanksbetweenthem.Forexamplethestatement

DOIVAL=QTO(A+3);
couldbewrittenmorecompactlyas
DOIVAL=QTO(A+3);
butitcouldnotbefurthercondensedto
DOIVAL=QTO(A+3);
ThelastexampleisinfactavalidPL/Istatementwithan
entirelydifferentmeaning.Acommentmaybeusedinany
placewhereablankcanappear.Acommentiswrittenasthe
characters"/*"followedbyasequenceofcharacters
notcontaining"*/",followedby"*/",e.g.,
/*THISISACOMMENT*/
Anidentifierconsistsofaletterfollowedbyanynumberof
letters,digits,andbreakcharacters"_",e.g.,
POPE_LEO_THE_15TH.Thesyntaxofmostoftheotherkindsof
tokensisdiscussedbelow.
Atextinclusionhastheform
%INCLUDEtextname;
Thetextnamereferstoanexternallystoredpieceoftext,
whichreplacesthetextinclusionwhentheprogramistrans
lated.Onaccountofthevariationinoperatingenvironments
ondifferentmachines,theinterpretationofthetextnameis
implementationdefined.Withthisfacility,itispossible
tousethesameversionofachunkofprograminmanydiffer
entexternalprocedures,evenoneswrittenbydifferent
programmers.
Keywordscanbeusedasidentifiers;inthisrespectPL/I
differsfromCOBOL,whichtreatskeywordsasreservedwords,

andfromALGOL,whichusesadistincttypefacetorepresent
them.Forexample,
IFIFTHENTHEN=ELSE;
isavalidsequenceofstatementsinPL/I.Thefirststatement
isanIFstatementthatteststhevariableIF;thesecondis
anassignmentstatementwhosetargetisthevariableTHEN.
Mostofthelongkeywordscanbeabbreviated,e.g.,CTLfor
CONTROLLEDorNOFOFLforNOFIXEDOVERFLOW.Thenamesofsome
builtinfunctionscanalsobeabbreviated.
TherearethreedifferentkindsofPL/Istatementsthat
headgroupsofstatements:theDOstatement,thePROCEDURE
statement,andtheBEGINstatement.Forallthree,thegroup
isendedbyanENDstatement.Ifastatementnameisattached
tothestatementthatheadsagroup,thenthesamestatement
namecanalsobeattachedtotheENDstatementthatterminates
thegroup,thusindicatingwhichstatementisclosedoutby
theEND.AsingleENDstatementcancloseoutmorethanone
group,however,asthefollowingexampleillustrates:
ALEPH:

PROCEDURE;

...
DO;
...
BEIT:

BEGIN;
...
ENDBEIT;
...
ENDALEPH;

ThefinalENDstatementclosesoutboththeleadingPROCEDURE
statementandtheDOstatementthatfollowsit.

DATATYPES
ThedifferentkindsofdatainPL/Icanbeclassified
intogroupscalleddatatypes,orsimplytypes.Theavail
abletypesareeitheraggregatetypesorscalartypes.An
aggregateiscomposedfromsimplertypes,andcanbeeither
anarrayorastructure.Arraysandstructuresarediscussed
below.Thescalartypescanbegroupedintoprintableand
nonprintabletypes,sometimesknownascomputationaland
noncomputational.Foreachtype,therecanbevariablesand
valuesofthattype;forsometypestherecanalsobe
constants.
Aconstantassociatesanamewithasingleunchanging
value,whileavariableassociatesanamewithalocation
whereavaluecanbestored.Thevalueofavariableisin
generaltimedependent.Variablesareintroducedintothe
programbyDECLAREstatements,e.g.,
DECLARELETTER_SEQUENCECHARACTER(15)VARYING;
whichdeclaresthevariableLETTER_SEQUENCEtohavecharacter
stringsoflengthfrom0to15asitsvalues.However,a
variablecanbedeclaredeventhoughnoDECLAREstatementis
writtenforit(see"Declarations"below),andcertainkinds
ofconstantsarealsointroducedthroughDECLAREstatements.
ArithmeticTypes
Theprintabletypesconsistofthearithmetictypesand
thestringtypes.Thearithmetictypesarecharacterizedby
fourkindsofattributes:thebase(binaryordecimal),

thescale(fixedorfloat),themode(realorcomplex)and
theprecision.Sinceallcombinationsofbase,scale,and
modearepermitted,thereareeightarithmetictypes,pre
cisionaside.Theprecisionofafixedtypeconsistsofa
numberofdigitsandascalefactor;thatofafloattype
consistsjustofthenumberofdigits.Forexample,the
typeREALFIXEDDECIMAL(6,2)(the"(6,2)"indicatesthe
precision)containsvaluesoftheformDDDD.DD,wherethe
D'saredecimaldigits.Ifthescalefactorisomitted,it
istakenaszero.Thebinarytypesaresimilar,except
thatbinaryratherthandecimaldigitsareused.Thefixed
andfloattypescorrespondtothefixedpointandfloating
pointarithmeticdataavailableonmostcomputers.FIXEDis
ageneralizationoftheintegertypefoundinanumberof
otherprogramminglanguages,sincetheintegertypedoesnot
provideforscaling.FLOATcorrespondstotherealtypeof
otherlanguages.Anotablefeatureofthefloattypesis
thattheycanbeusedtoexpressthedesiredaccuracyofa
numericalcomputationindependentlyofthewordlengthof
thecomputercarryingoutthecomputation.
Thetypeofanarithmeticconstantisindicatedbyits
form.Arealfixeddecimalconstantconsistsofasequence
ofdecimaldigitswithanoptionaldecimalpointandsign,
e.g.,17.76.Fixedconstantscanbescaled;forinstance,
78F4hasthevalue0.0078,obtainedbymultiplying78by104
Arealfloatdecimalconstantconsistsofarealfixeddecimal
constantfollowedbyanexponentpartindicatedbytheletterE,

10

e.g.,4.832E+12.Binaryconstantsareformedsimilarly,
exceptthatonlybinarydigitsareused,andthenumberis
followedbytheletterB,e.g.,10.1Bor11E16B(designating
31016).Complexconstantsdonotexistassuch;acomplex
constantisformedasthesumofarealconstantandanimag
inaryconstant,e.g.,4+3I.
StringTypes
Thestringtypesarecharacterandbit,eachofwhich
inturnmaybevaryingornonvarying.However,stringvalues
aresequencesofcharactersorbits,andthevaryingandnon
varyingattributesarenotappliedtothem.Eachstringtype
hasamaximumlengthassociatedwithit;forthenonvarying
types,theactuallengthisalwaysequaltothemaximum
length.Forinstance,thetypeCHARACTER(14)VARYINGdescribes
characterstringswhoselengthvariesfrom0to14characters,
whilethetypeBIT(8)NONVARYING(NONVARYINGisthedefault)
describesbitstringsthatarealwaysexactly8bitslong.
Acharacterstringconstantiswrittenasasequenceof
charactersenclosedinsinglequotes,withinternalquotes
doubled,e.g.,
'THEFARMER''SDAUGHTER'
Thenullcharacterstring,whichcontainsnocharacters,is
writtenas''.Abitstringconstantiswrittenasasequence
ofbinarydigitsenclosedinsinglequotesandfollowedbyB,
e.g.,'l0l00l'B;thenullbitstringiswrittenas''B.Bit
stringscanalsobewritteninbase4,base8,orbase16

11

notation.Forinstance,'7400'B3indicatesthebase8(octal)
constant7400(equivalentto'111100000000'B),while'A81'B4
indicatesabase16constant.(ThedigitaftertheBindicates
apowerof2.)Thisextendednotationisnotavailablefor
binaryarithmeticconstants.Theonebitvalues'1'Band'0'B
areparticularlyuseful,astheyaretheresultsreturnedby
thePL/Icomparisonoperators;'1'Brepresentstrueand'0'B
representsfalse.
Whenastring,eitherbitorcharacter,isdeclared,the
maximumlengthneednotbegivenbyaconstant,sothatthe
declaration
DECLARENEWSTRCHARACTER(Kl+2);
ispermissible.TheexpressionKl+2mustbewelldefinedat
thetimethatNEWSTRiscreated.Stringsthatappearas
parametersofproceduresmayhavetheirmaximumlengthsgiven
by*,e.g,
DECLAREPARAM_3CHARACTER(*);
Inthiscase,themaximumlengthofPARAM_3isdeterminedby
theargumentcorrespondingtoPARAM_3.Stringsusedaspara
metersmusthavetheirmaximumlengthsgiveneitherby*or
byanexpressioncomposedpurelyofconstants;moregeneral
expressionsarenotpermitted(butarenotparticularlyuseful
inthiscontextinanycase).

12

PicturedTypes
ThepicturedtypesarederivedfromsimilartypesinCOBOL,
butaremoregeneral,Apicturedtypehasanassociatedpicture,
e.g.,999V.99,thatdescribestheappearanceofthevaluesof
thattype.Thevaluesarerepresentedascharacterstrings,and
thesemanticsofPL/Iaresuchthatanimplementationisactually
obligedtostorethemthatway.Therearenoconstantsof
picturedtype.Picturescanbeusedininputoutputformatsas
wellasindeclarations;anexampleofthedeclarationofa
picturedtypeis
DECLARESALARYPICTURE'$$$,$$$V.$$';
Apicturedtypehasapictureassociatedwithit.The
pictureisgivenbyacharacterstring.Withinthepicture,
parenthesizedcountscanbeusedtoindicaterepeatedcharacters,
sothatthepicture'$$$$$'canalsobewrittenas'(5)$'.
Apicturecanbeeitheracharacterpictureoranumeric
picture.Anumericpicturedtypecontains,inadditiontothe
pictureitself,amodespecification(eitherREALorCOMPLEX).
Characterpicturesarerathersimple.Theyconsistof
justthecharactersA,9,andX.ThecharacterAstandsfor
aletterorablank;thecharacter9standsforadigitora
blank;andthecharacterXstandsforanything.Character
picturesareusedtovalidatestrings,i.e.,toinsurethat
theyareintheproperform.Thus,ifwehavethedeclaration
DECLARESTRING_TESTPICTURE'(3)AXX9';
wecanassigntoSTRING_TESTvaluesconsistingofthreeletters

13

(orblanks)followedbyanytwocharactersfollowedbya
singledigit(orblank).Iftheassignedvaluedoesnot
havethesecharacteristics,anerrorwillbesignalled.
Anumericpictureisonethatcontainsacharacterother
thanA,9,orX.Bythisdefinition,apictureconsistingof
all9'sisacharacterpictureratherthananumericpicture.
Anumericpicturedtypehasanassociatedarithmetictype,
whichisdeterminedbytheformofthepicturetogetherwith
themode.Thepictureitselfisindependentofthemode.
Thusifwehavethedeclarations
DECLARERPICREALPICTURE'ZZZ';
DECLARECPICCOMPLEXPICTURE'ZZZ';
RPIChasanassociatedarithmetictypeofREALFIXEDDECIMAL(3,0),while
CPIChasanassociatedarithmetictypeofCOMPLEX
FIXEDDECIMAL(3,0).(Theassociatedarithmetictypeisneces
sarilydecimal.)Ifthepicturecontainseitherofthe
charactersEorK,itisafloatpicture(i.e.,itsassociated
arithmetictypeisfloat);otherwise,assumingitisnumeric,
itisafixedpicture.Theassociatedarithmetictypecanbe
thoughtofasspecifyingthemeaningofthevalues,asdistinct
fromtherepresentationofthevalues.Themeaningbecomes
importantwhenpicturedvaluesareusedinarithmeticoperations.
Whenanumericvalueisassignedtoapicturedvariable,
thevalueiseditedtoconformtothepicture.Thecharacters
inthepicturedeterminehowtheeditingistobedone,assuming
thatthevaluehasalreadybeenconvertedtotheassociated

14

arithmetictype.Editingbymeansofapictureisillustrated
bythefollowingexample:Supposethatthevalue34.8isto
beeditedusingthepictureS9999V.99.Thenthepicturedvalue
willbe+0034.80.InthisexampletheSindicatesanexplicit
sign,the9'sindicateexplicitdigits,theVindicatesan
implicitdecimalpoint(usedtoalignthenumericvaluewith
thecharactersofthepicture)andtheperiodisaninsertion
character.Themeaningsofthedifferentpicturecharacters
aregiveninTable1,andtheiruseisillustratedinTable2.
TheI,R,andTcharactersrepresentdigitswithsign
overpunching,i.e.,thesignoftheentirevalueiscombined
withthedigittoformasinglecharacter.Signoverpunching
isthestandardinputconventionforCOBOL;onakeypunch,
thecharactersareformedbypunchingbothasign(11rowfor,
12rowfor+)andadigitinasinglecolumn.AlthoughCRand
DBaretwocharactersratherthanone,thetwocharacters
alwaysgotogether,andareusedtoindicateanegative
quantity.CRstandsfor"credit"andDBfor"debit".
Thedriftingcharacters$,Z,+,,andSareusedtoedit
leadingzerosintoblanks.Whenasequenceofdriftingcharac
tersappears(theymustallbethesameone),thecharacter
driftstothepositiontotheleftoftheleadingnonzerodigit
inthevalue,andtheremainingpositionstotheleftare
blankedout.Anyinsertioncharacterswithintheblankedout
positionsarethemselvesblankedout.
Theperiodisatrueinsertioncharacter,inthatits
presenceorabsencehasnoeffectonthevaluerepresentedby

15

thepicture.TheperiodneednotappearnexttotheV,even
thoughthesequence"V."isoftenused.Asingle$,S,+,or
canbeplacedatthebeginningorattheendofapicture,in
whichcaseitsignifiesanexplicitinsertionratherthana
driftingposition.Forinstance,thevalue92editedbythe
picture'(5)$V.$$S'yieldsthestring'$92.00+';inthis
casetheScausesasigntobeinserted,andisnotadrifting
character.
Althoughpicturesareordinarilyusedtoeditrealvalues,
theycanbeusedtoeditcomplexvaluesalso.Whenavariable
isdeclaredtobepicturedandcomplex,thepictureisused
toeditboththerealandimaginarypartsofanycomplexvalue
assignedtothevariable,andthetwopartsareconcatenated.
However,thereisnowaytousepicturestoinsert"I"into
theeditedrepresentationofacomplexnumber.

16

Table1.MeaningofPictureSymbols

(a)Characterpicturesymbols
A

alphabeticcharacter

digitorblankpermitted

anythingpermitted

(b)Numericpicturesymbols
9

digit

digitwithzeromappedtoblank

digitwithzerosuppression

driftingorinserteddollarsign

driftingasterisk(checkprotection)

driftingorinsertedsignforpositivevalues

driftingorinsertedsignfornegativevalues

driftingorinsertedsignforallvalues

CR

creditsymbol,insertedfornegativevalues

DB

debitsymbol,insertedfornegativevalues

digitwithpositivevalueindicatedbyoverpunch

digitwithnegativevalueindicatedbyoverpunch

digitwithsignalwaysindicatedbyoverpunch

insertedperiod

insertedcomma

insertedblank

insertedslash

implieddecimalpoint

startofexponent,Einserted

startofexponent,nothinginserted

17

Table2.ExamplesofNumericPictures
Picture
999
99V9
YY/YY/YY
ZZZZ
Z,ZZZ
Z,ZZZ
Z.VZZS
Z.VZZ+
ZV.ZZ+
ZZZZ$
+ZZZZ$
ZZ99
$$V.$$
$$B$$$
$$B$$$
+++

SSS
$***V.**
$***.V**
$$$99CR
$$$99CR
$$$99DB
999T
999T
I999
I999
ZZZR
ZZZR
99.V999BKS99
V.99999E99
999V9F3
99999F2

NumericValue
7
7
760404
23
123
1234
1.6
.03
0.03
2
2
0
1.23
2345
345
6
6
6
.07
.07
8
123
123
71
71
1776
1776
71
71
123456
123
12345
12.34

Note:Aindicates1withpositiveoverpunch.
Jindicates1withnegativeoverpunch.

18

PicturedString
7
70

76/

4/
5

23

123

1234

1.6

03+

.
03+

2$

+2$

00

$1.23

$2
345

$345

+6

+6
$***.07
$****07

$08

$123CR

$123DB

07A
07J
A776
1776
71
7J

1.2346

+04

.12300E03
0123
01234

Pointers,AreasandOffsets
ThenonprintabletypesofdatainPL/Iarepointers,areas,
offsets,files,labels,entries,andformats.Apointercan
bethoughtofasthelocationofapieceofdata;itresembles
theref(reference)notionofAlgol68.However,pointer
variablesinPL/Iareuntyped;thatis,apointervariable
cancontainapointertodataofanytypewhatsoever.The
onlypointerconstantisthenullpointer,whichdoesnot
pointatanythingandthereforedoesnotcompareequaltoany
pointertoanexistingobject.Thenullpointerisobtained
asthevalueofthebuiltinfunctionNULLofnoarguments.
Pointersareusedinconjunctionwithbasedvariables,which
actastemplatesforanareaofstorage.Basedvariablesare
discussedbelow.
Anareaisaregioninwhichspaceforbasedvariables
canbeallocated.Areascanbeclearedoftheirallocations
inasingleoperation,thusallowingforwholesalefreeing.
Moreover,areascanbemovedfromoneplacetoanotherby
meansofassignmenttoareavariables,orthroughinputoutput
operations.Thereisoneareaconstant,theemptyarea,
whichisobtainedasthevalueofthebuiltinfunctionEMPTY
ofnoarguments.Assignmentoftheemptyareatoanyarea
variableclearstheareaofitsallocations.Moreprecisely,
theoldvalueofthevariableisdestroyed(thoughacopymay
existelsewhere),andthenewvalueisanareawithnothing
allocatedinit.Thedeclarationofanareaspecifies(at

19

leastbydefault)anareasizeinimplementationdefinedunits
(bytes,words,etc.),e.g.,
DECLARESTRUCTURE_AREAAREA(2000);
Whenanareaismoved,pointerstoobjectswithinthearea
losetheirvalidity.Therefore,PL/Ialsoprovidesoffsets,
whicharepointersrelativizedtotheoriginofagivenarea.
Whenanareaismoved,theoffsetsoftheobjectswithinthe
arearemainunchanged.Conceptually,pointersandoffsetsare
relatedbytheequation
pointer=offset+area
butinanactualimplementationthatequationneednothold.
Thereisoneoffsetconstant,thenulloffset,whichisobtained
byconvertingthenullpointertoanoffset.
Tomakeiteasiertoworkwithoffsets,itispossible
todeclareanoffsetwithanimplicitareaassociation(which
canbeoverridden),e.g.,
DECLAREOFF_FROM_A3OFFSET(A3);
DECLAREA3AREA(300);
WhenOFF_FROM_A3isreferencedinacontextwhereapointeris
required,theoffsetvalueinOFF_FROM_A3isconvertedtoa
pointerrelativetotheareaA3.
Files
Afileis,conceptually,aportthroughwhichcommunication
isestablishedbetweentheprogramandadataset.Adataset,
inturn,isacollectionofinformationresidingonanexternal

20

medium,accessibletotheprogramonlythroughinputoutput
operations.Duringthecourseofexecutionofaprogram,
agivenfilemaybeconnectedtodifferentdatasets,orto
nodataset,atdifferenttimes.Inputoutputoperations
referenceafile,whichmustbeconnectedtoanappropriate
dataset;theoperationsthentakeplaceonthedataset.Afile
connectedtoadatasetissaidtobeopen;onenotconnected
toadatasetissaidtobeclosed.
Thefileitselfisafilevalue;eachfilevalueis
uniquelyassociatedwithafileconstant,declared,forexample,
by
DECLAREFILECONFILECONSTANT;
Filevariablesaredeclaredsimilarly,e.g.,by
DECLAREFILEVARFILEVARIABLE;
IfneitherCONSTANTnorVARIABLEisspecifiedinthedeclaration,
theusualdefaultisCONSTANT.Moreover,declarationsoffile
constantsareintroducedimplicitlyinanumberofcontexts,
sothatinpracticetheprogrammerrarelyneedstowritethese
declarations.Forinstance,thePL/Istatement
PUTLIST(A,B);
causesthevaluesofAandBtobewrittenontothedataset
associatedwiththefilenamedSYSPRINT(assumedsincenoother
filewasspecifiedinthePUTstatement).Ifnodeclarationis
explicitlygivenforSYSPRINT,thedeclaration
DECLARESYSPRINTFILECONSTANT;

21

isassumed.WhenthePUTstatementisexecuted,thefile
SYSPRINTisopenedasaPRINTfile(assumingitisnotalready
open).
Labels
Alabelisanameattachedtoanexecutablestatementso
thatcontrolcanbetransferredtothatstatementbymeansof
aGOTOstatement.Alabelvaluehastwocomponents:adesignator
(suchasanaddress)ofthestatementnamedbythelabel,and
anenvironment,whichrecordsthestateofexecutionofthe
programatthetimewhentheblockcontainingthelabelwas
entered.Theenvironmentisnecessarybecausetheaddressby
itselfdoesnotalwaysprovidesufficientinformationtodeter
mineunambiguouslythestateofexecutionafteraGOTOstatement
hasbeencarriedout(seethesection"EntryValuesandEnviron
ments"below).
Labelconstantsaredeclaredbytheappearanceofalabel
asastatementname,asin
BOOK_FOUND:VOLUME=FOLIO(J);
whichdeclaresBOOK_FOUNDasalabelconstant.Infact,label
constantscannotbedeclaredinanywayotherthanbytheir
appearanceasstatementnames.Notallstatementnamesdeclare
labelconstants,however;someofthemdeclareentryconstants
andformatconstants.Thetypeofconstantdeclaredbya
statementnameisdeterminedbythetypeofstatementtowhich
itisattached.Labelvariablesaredeclaredusingthe
attributeLABEL,e.g.,

22

DECLARELABVARLABELVARIABLE;
Astatementnamecanbewrittenwithoneormoresubscripts,
andbythisconventionconstantarraysoflabelscanbecreated.
Forinstance,ifablockcontainsexecutablestatementswiththe
statementnamesCASE(l),CASE(0),CASE(1),andCASE(2),the
appearanceofthesestatementnamesconstitutesadeclaration
ofCASEasaconstantarrayoflabels,whosesinglesubscript
hasalowerboundof1andanupperboundof2.Itisquite
permissibletoattachseveralofthesesubscriptedstatement
namestoasinglestatement,togivetheminnonincreasing
order,toattachthemtostatementsalsobearingnonsubscripted
statementnames,oreventoomitsomeindexvaluesfromtheset.
Forinstance,ifCASE(0)wereomittedfromtheaboveset,the
setwouldstillbevalid,butatransfertoCASE(0)wouldbe
inerror.Typically,anelementofaconstantarrayoflabels
isselectedbyastatementsuchas
GOTOCASE(CASE_NUMBER);
Entries
Anentryisanentrypointtoaprocedure(see"Procedures,
Scopes,andEnvironments"below)treatedasadatum.Anentry
constantisdeclaredbytheappearanceofastatementname
attachedtoaPROCEDUREstatementoranENTRYstatement.For
instance,
PROCESS_NAME:PROCEDURE(NAME,SPECS);
declaresPROCESS_NAMEasanentryconstant,whoseassociated

23

valueisthe(single)entrypointtotheprocedureheadedby
thePROCEDUREstatement.Entryvalues,likelabelvalues,
carryenvironmentswiththem.Entryvariablesandarraysof
entryconstantsareavailable.Atypicalapplicationofan
entryvariablearisesinwritingaproceduretointegratean
arbitraryfunction;withintheprocedure,thefunctionis
declaredasanentryvariable(andaparameter),andthe
actualfunctiontobeintegratedispassedasanargument.
Whenanexternalprocedurereferencesanentryin
anotherexternalprocedure,thenthefirstproceduremust
declarethesecondexplicitlyasanentryconstant,asin
DECLARESEARCHVALEXTERNALENTRY(CHARACTER(*))
RETURNS(FIXED);
TheCONSTANTattributeisassumedbydefaultinthiscase.
TheprocedurecontainingthisdeclarationexpectsSEARCHVAL
tobeanentrytoanexternalprocedure,whoseexpectedargu
mentisacharacterstringofunspecifiedlength,andwhich
returnsafixedvalue.
Formats
Aformatisusedtospecifytheformofdataonadataset
accessedthroughastreamfile(see"EditDirectedInputOutput"
below).Aformatconstantisdeclaredbytheappearanceofa
statementnameonaFORMATstatement,e.g.,
FMT3:FORMAT(SKIP,3A,X(M),A);
Aswithlabelsandentries,formatvariablesandarraysof
formatconstantsareincludedinPL/I.Formatvariables

24

aredeclaredusingtheattributeFORMAT,e.g.,
DECLAREFMTVARFORMATVARIABLE;
Sinceformatscancontainreferencestovariables,e.g.,the
MintheexampleFMT3above,formatvaluescarryenvironments.
Arrays
TwotypesofaggregatesareprovidedinPL/I:arrays
andstructures.Anarrayisacollectionofelementsallhaving
thesametype;aparticularmemberofthecollectionisselected
usinganappropriatesequenceofsubscripts.Astructure,on
theotherhand,isacollectionofelementshavingpossibly
differenttypes;aparticularmemberofthecollectionis
selectedbyusinganappropriatenameastheselector.A
powerfulfeatureofPL/Iisthatitallowsaggregatestobe
treatedasdataobjectsinmostcontexts,sothatitis
possible,forinstance,toaddtwoarraysinasingleopera
tion,ortowriteaprocedurethatreturnsastructureasits
value.
Anarrayischaracterizedbyasequenceofdimensions;
thedimensionalityofthearrayisthenumberofitsdimensions.
Eachdimensionhasalowerboundandanupperbound,andthese
canbearbitraryintegers.Forexample,thedeclaration
DECLAREMESH(100:100,200)FLOATBINARY(40);
declaresMESHtobeatwodimensionalarray.Thefirstsub
scripthaslowerbound100andupperbound100,whilethe
secondhaslowerbound1(assumedsincenoneisgiven)and

25

upperbound200.Whenreferenceismadetoanelementofan
array,thesubscriptscanbearbitraryexpressions,aslongas
thevaluesofthoseexpressionscanbeconvertedtointegers.
Aswithcharacterstrings,boundscanbegivenbyexpres
sionsaswellasconstants.Foranarrayparameter,apairof
bounds(notasingleone)canbegivenby*.The*canalso
beusedinaquitedifferentsensetoindicateacrosssection
ofanarray.Forinstance,MESH(3,*)designatesaonedimaisional
array,withlowerbound1andupperbound200,consistingof
thoseelementsofMESHwhosefirstsubscriptis3.Anynumber
ofthesubscriptsinanarrayreferencecanbereplacedby*'s;
thedimensionalityoftheresultingarrayisthenumberof*'s.
Arrayvariablestakeonarrayvalues.Arrayvaluescan
ariseduringtheevaluationofanexpression,e.g.,whentwo
arraysareaddedtogether.Asidefromlabels,entries,and
formats,therearenoarrayconstantsinPL/I.
Structures
Astructureisacollectionofnamedelements,eachof
whichcanitselfbeastructure.Anexampleofatwolevel
structuredeclarationis
DECLARE
1EMPLOYEE_RECORD,
2NAME,
3FIRSTCHARACTER(10)VARYING,
3MIDDLE_INITIALCHARACTER(1),
3LASTCHARACTER(15)VARYING,
2ID_NUMBERFIXEDDECIMAL(9),
2SALARYFIXEDDECIMAL(7,2);

26

Thenumberinfrontofeachcomponentisalevelnumber.The
structureasawholeisatlevelone.Themembersofthe
levelonestructurearetheleveltwocomponents;thoseof
theleveltwocomponentsarethelevelthreecomponents,etc.
Itispossibletowritestructuredeclarationsusingnonconse
cutivelevelnumbers,butthereisalwaysanequivalent
structureusingconsecutiveones.Inanyevent,thelogical
levelsarealwaysconsecutivelynumbered.
Theorganizationofastructuredvalueisjustlikethat
ofastructuredvariable.Astructuredvaluecontainsanumber
ofcomponents,andcanbetreatedasasingleobject.For
example,twostructurescanbeaddedjustastwoarrayscanbe
added.Therearenostructureconstants.
Theelementsofastructurearereferredtousing
qualifiednames,althoughabbreviatedversionsarepermissible.
Thefullyqualifiednamesoftheelementsofthestructure
givenaboveare:
EMPLOYEE_RECORD

(itselfastructure)

EMPLOYEE_RECORD.NAME

(itselfastructure)

EMPLOYEE_RECORD.NAME.FIRST
EMPLOYEE_RECORD.NAME.MIDDLE_INITIAL
EMPLOYEE_RECORD.NAME.LAST
EMPLOYEE_RECORD.ID_NUMBER
EMPLOYEE_RECORD.SALARY

Abbreviatedversionsofqualifiednamesareobtainedbyleaving
outanyofthecomponentidentifiersotherthanthelastone.

27

Theseabbreviatedformscanbeusedaslongastheresultis
notambiguous,i.e.,aslongasitcannotrefertomorethan
oneobject.
Arraysofstructuresandstructuresofarraysarepossible,
andcanbenestedtoanydepth.Anexampleofsuchanested
structureisgivenby:
DECLARE
1CAR(30),
2COUNTRY_OF_ORIGINFIXEDDECIMAL(3),
2DEALERS(40),
3CITYCHARACTER(20)VARYING,
3STATECHARACTER(2),
3COMPANYCHARACTER(30)VARYING;
Insuchanestedentity,dimensionalityisinherited.Thus
CITYisatwodimensionalarraysinceonedimensionisinherited
fromCARandtheotherfromDEALERS.CITY(*,17)designates
thearraycomposedoftheelements
CAR(l).DEALERS.CITY(17)
CAR(2).DEALERS.CITY(17)
...
CAR(30).DEALERS.CITY(17)
InwritingareferencetoanelementofCITYorasimilar
object,thesubscriptscanbewritteninanypositionaslong
astheyareintherightorder.ThusCITY(*,17)couldalso
havebeenwrittenasCAR(*).CITY(17)orasDEALERS(*,17).CITY.

28

DECLARATIONS
Adeclarationassociatesasetofattributeswithan
identifier.Theattributesspecifythecharacteristicsofthe
objectdenotedbytheidentifier,suchasitsdatatype.
Withinanexternalprocedure,agivenidentifiercanbedeclared
morethanonce,sincetheidentifiercanbedeclaredindiffer
entblocks,orasamemberofdifferentstructures,orboth.
Nevertheless,eachdeclarationofanidentifierdesignatesa
distinctobjecthavingitsownattributes.Therulesforname
resolutiondeterminehowanoccurrenceofanidentifieris
resolvedtotheappropriatedeclaration(see"BlocksandScopes"
below).
Everyoccurrenceofanidentifierwithinanexternal
proceduremusthaveacorrespondingdeclarationwithinthat
externalprocedure.Moreover,everydeclarationmusthavea
completeandconsistentsetofattributes.Tosatisfythese
principles,PL/Iincludesextensiveconventionsfordefaulting
declarations,i.e.,forcreatingdeclarationsthatwerenot
writtenintheprogramandfordeducingattributesofincomplete
declarations.
Manifest,Explicit,Contextual,andImplicitDeclarations
AnidentifierthatisdeclaredinaDECLAREstatement
writtenbytheprogrammerissaidtobemanifestlydeclared.*

*Theterm"manifest",thoughconvenient,isnotstandard
usage.

29

Anidentifierthatismanifestlydeclared,orthatappearsin
aparameterlist,orappearsasastatementname,issaidto
beexplicitlydeclared.Anidentifierappearinginaparameter
listmay,butneednot,bemanifestlydeclared;anidentifier
appearinginastatementnamemustnotbemanifestlydeclared.
Ifanidentifierappearsinaprocedureandnoexplicit
declarationexistsforthatidentifier,thenadefaultdeclara
tioniscreatedifpossible.Thedefaultdeclarationisplaced
intheoutermostblockoftheexternalprocedure.Ifthe
identifierisusedinsuchawayastosuggestwhatits
attributesshouldbe,itissaidtobecontextuallydeclared;
otherwiseitisimplicitlydeclared.Forinstance,ifthe
identifierOUThasnotbeenmanifestlydeclaredandthestate
ment
PUTFILE(OUT)LIST(VALX,VALY);
appears,thenOUTwillbecontextuallydeclaredwiththeattri
butesFILEandCONSTANT.Similarly,iftheidentifierEXPhas
notbeenmanifestlydeclaredandthestatement
Y=EXP(A**2);
appears,EXPwillbecontextuallydeclaredwiththeattribute
BUILTIN.Aprogramisinerrorifitinducesconflicting
contextualdeclarations.
Animplicitdeclarationiscreatedforanidentifier
ifitisdeclaredneitherexplicitlynorcontextually.In
thiscase,thecreateddeclarationinitiallyhasnoattributes,
andalltheattributesareaddedbydefaultlateron.

30

DeclarationsofStatementNames
Theappearanceofanidentifierasastatementname
completelydeterminesitsattributes.Thedatatypeofthe
identifierisdeterminedbythekindofstatementnamed,as
wellaswhetherornottheidentifierissubscripted.Ifthe
namedstatementisanENTRYstatementoraPROCEDUREstatement,
theidentifieracquirestheattributesENTRYandCONSTANT;if
thenamedstatementisaFORMATstatementtheidentifier
acquirestheattributesFORMATandCONSTANT;andifitisany
otherstatementtheidentifieracquirestheattributes
LABELandCONSTANT.Moreover,ifthestatementnameissub
scripted,thentheidentifieracquiresanappropriate
DIMENSIONattribute.
Theimplieddeclarationofanentryconstantcannotbe
fullyconstructeduntilthetypesofitsparametersareknown.
Whentheparametertypesareknown,theentryconstantcanbe
characterizedcompletely.Atthatpointtheparameterspeci
ficationsandtheRETURNSattribute,ifany,areaddedtothe
declaration.Forinstance,thestatements
FN: PROCEDURE(A,B)RETURNS(CHARACTER(12)VARYING);
DECLAREACHARACTER(*);
DECLAREBPOINTER;
...
ENDFN;
leadtothederiveddeclaration
DECLAREFNENTRY(CHARACTER(*),POINTER)
RETURNSCHARACTER(12)VARYING)CONSTANT;

31

AttributeConsistencyandCompleteness
ThediagramofFigure2canbeusedtodeterminewhether
asetofattributesisconsistentandcomplete,exceptfora
fewpeculiarcases.Inthisdiagram,thefollowingconventions
arefollowed:
1. Doublelinesindicatethedefinitionofaterm.
2. Rectanglesindicatespecificattributes.Ifarectangle
isdashed,itindicatesanoptionalattribute.
3. Ovalsindicatesetsofattributes.
4. Horizontallinesindicatesetsforwhichall(nondashed)
elementsmustbepresent).
5. Verticallinesindicatesetsfromwhichonealternative
mustbechosen.
Asetofattributesiscompleteandconsistentifitcanbe
constructedfromthisdiagram;itisconsistentifitisa
subsetofacompleteandconsistentset.
Theinterpretationofthisdiagramisillustratedbythe
attributeset
INTERNALVARIABLEAUTOMATICALIGNEDPOINTERINITIAL
Startingfromthenode"consistentset",ascopeandadeclara
tiontypemustbothbechosen.ThescopecanbeeitherINTERNAL
orEXTERNAL;INTERNALischosen.Thedeclarationtypecanbe
avariable,anamedconstant,etc.;itischosentobea
variable.Inthatcase,theattributeVARIABLEmustbepresent,
aswellasastoragetypeandadatadeclaration.The
storagetypeischosentobeastorageclass;thestorageclass

32

33

34

35

ischosentobeAUTOMATIC.Thedatadescriptionmay,but
neednot,containDIMENSION;inthiscaseitdoesnotcontain
DIMENSION.Thedatadescriptionmustalsocontainanalignment,
chosentobeALIGNED,andeitheradatatypewithoptional
INITIAL,orSTRUCTURE.Inthiscase,INITIALispresent
(theactualinitialvaluesareignored).Thedatatypeis
chosentobenoncomputational.Ofthealternativesfornon
computationaltype,locatorisselected;ofthealternatives
forlocator,POINTERisselected.Thustheentiresetof
attributesisshowntobecompleteandconsistent.(Theorder
inwhichtheattributesaregivenisimmaterial.)
Notallconsistencyviolationsareshownupbyreference
tothisdiagram.Forexample,thecombination
AUTOMATICEXTERNAL
andthecombination
STATICLABELINITIAL
arebothinvalid,butpassthetestofthediagram.Specific
auxiliaryrulesareneededinordertodisallowtheseand
similarcases.Therequirementforcompletenessisrelaxed
forthecaseoffileconstants,i.e.,declarationswiththe
attributesFILEandCONSTANT;althoughthefiledescriptionset
mustbeconsistent,itneednotbecomplete.
Certainattributeseitherpermitorrequiresubspecifica
tion;thesearelistedinTable3.Forexample,theBASED
attributepermits,butdoesnotrequire,thesubspecification
ofanauxiliarypointer(see"BasedStorage"below),whilethe

36

Table3.AttributesRequiringorPermittingSubspecification
A.SubspecificationRequired
Attribute

Required
Specification

CHARACTER

length

BIT

length

AREA

sizeofarea

DIMENSION

dimensionality

RETURNS

typeofreturnedvalue

PRECISION

numberofdigits,possiblescalefactor

PICTURE

picturespecification

GENERIC

genericspecification

ENTRYwithCONSTANT

parametertypes

POSITION

positioncount

DEFINED

basevariable

LIKE

likenedvariable

B.SubspecificationPermitted
Attribute

Permitted
Subspecification

BASED

basingpointer

OFFSET

area

ENTRYwithVARIABLE

parametertypes

37

CHARACTERattributerequiresthesubspecificationofastring
length.
TheENTRYattributeandtheRETURNSattributethemselves
containattributesetsassubspecifications.Theseattribute
setsareknownasdescriptors,andmustalsobecompleteand
consistent.ThedescriptorsintheENTRYattributedescribe
theparametersexpectedbyaprocedure,whilethedescriptors
inaRETURNSattributedescribethevaluereturnedbyaproce
dure.*Tobecompleteandconsistent,adescriptormustbe
derivablefromthe"datatype"nodeinthediagramofFigure2,
butmayoptionallycontaintheMEMBERattribute.Thedescriptor
forastructureasawholelookslikethedeclarationofa
structurevariablewiththeidentifiersleftoff,e.g.,
DECLAREGENFUNCENTRY(
1(*),
2FIXEDBINARY,
2CHARACTER(30)VARYING);
StandardandUserDefinedDefaults
ThePL/Idefaultingrulesspecifyhowanincompletebut
consistentsetofattributesistobecompleted.Although
thereisastandardsetofdefaultingrules,theDEFAULT
statementcanbeusedtooverridethem.Thedefaultingrules,
whetherstandardoruserdefined,consistofapredicateand
adefaultattributeset.Thepredicateindicatesatestto
beappliedtotheattributesalreadypresentinthedeclaration

*Sinceprocedurescanacceptstructuresasargumentsand
canreturnstructuresasvalues,thespecificationofa
singleparameterorofareturnedvaluecancontainmore
thanonedescriptor.

38

(ordescriptor),whilethedefaultattributesetindicates
additionalattributestobesuppliedprovidedthattheyare
consistentwiththeonesalreadypresent.Inconsistency,in
thiscase,isnotanerror;itsimplymeansthatthedefault
isnotapplied.
Theprincipalstandarddefaultingrulesare:
1.AddtheattributesFIXED,REAL,andBINARY.Forinstance,ifFIXEDalone
ispresent,REALandBINARYareadded*
2.Ifthearithmeticattributesarepresentbutnoprecision
hasbeenspecified,addanimplementationdefinedprecision
whosesubspecificationdependsonthearithmeticattri
butesalreadypresent.
3.IfCHARACTERorBITispresent,assumeNONVARYING.
4.IfCHARACTERorBITispresentbutnolengthhasbeen
specified,assumealengthof1.IfAREAispresentbut
noareasizehasbeenspecified,assumeanimplementation
definedvaluefortheareasize.IfPOSITIONispresent
butnocounthasbeenspecified,assumeacountof1.
5IfneitherVARIABLEnorCONSTANThasbeenspecified,
assumeVARIABLEunlessENTRYorFILEispresent.IfENTRY
orFILEispresentbyitself,assumeCONSTANT.IfENTRY
orFILEispresentalongwithotherattributes,thedefault
dependsonwhatthoseotherattributesare.
6IfFILEandCONSTANT,orENTRYandCONSTANT,orCONDITIONispresent,
assumethatthescopeisEXTERNAL;inall
othercasesassumethatitisINTERNAL.

*ThisrulediffersfromtheoneusedinthewellknownIBM
implementationofPL/I.

39

7.IfEXTERNALispresent,assumethatthestorageclassis
STATIC;inallothercasesassumethatitisAUTOMATIC.
8.IfCHARACTERorBITispresent,assumeUNALIGNED;
otherwiseassumeALIGNED.*
Asaconsequenceofthedefaultingrules,animplicitlydeclared
identifier,whichstartswithanemptyattributeset,will
acquiretheattributeset
REALFIXEDBINARYPRECISION(d1,0)VARIABLEINTERNAL
AUTOMATICALIGNED
Hered1,istheimplementationdefineddefaultnumberofdigits
fortheattributecombinationFIXEDBINARY.Similarconstants
d2,d3,andd4arespecifiedforFIXEDDECIMAL,FLOATBINARY,
andFLOATDECIMAL.
TheDEFAULTstatementcontainsapredicateandoneormore
defaultattributesets.Declarationsarecompletedbyapplying
theusersuppliedDEFAULTstatementsintheorderthatthey
appearintheprogram,andthenapplyingthesystemdefault
rules.UnlikeDECLAREstatements,DEFAULTstatementsareorder
dependent.Adefaultattributesetisaddedifandonlyif
theappropriatepredicateissatisfiedandnoneoftheelements
inthesetleadstoaconflict.Thepredicatecanincludeboth
attributesandidentifierranges,indicatedbythekeyword
RANGE.Thepredicateisformedasabooleancombinationof
attributesandranges.RANGE(*)issatisfiedbyanyidentifier,
butnotbyadescriptor.RANGE(al:a2)issatisfiedbyany

*Thisruledoesnotapplytostructures.Thealignmentofa
structure,ifgivenexplicitly,ispasseddowntoallelement
arymembersofthestructureunlessaconflictingalignment
isgivenatalowerlevel.

40

identifierstartingwithaletterbetweenalanda2inclusive,
whileRANGE(init)issatisfiedbyanyidentifierstarting
withinit.Forinstance,
DEFAULT(RANGE(AB)|FLOAT&BINARY)COMPLEXSTATIC;
appliedtothedeclaration
DECLAREAB35FIXED;
yields
DECLAREAB35FIXEDCOMPLEXSTATIC;
andappliedtothedeclaration
DECLAREXYZFLOATDECIMAL;
yields
DECLAREXYZFLOATDECIMALCOMPLEXSTATIC;
However,ithasnoeffectwhenappliedto
DECLAREAB35REALFIXED;
sinceCOMPLEXconflictswithREAL.Italsohasnoeffectwhen
appliedto
DECLAREXYZFLOATBINARY;
sincethepredicateisnotsatisfied.
TheLIKEAttribute
TheLIKEattributecanbeusedtocopypartofastructure
declarationintoanotherdeclaration.Itisusefulwhena
programusesmanysimilarlyorganizedstructures.Forinstance,
ifaprogramincludesthedeclarations

41

DECLARE
1ASSEMBLYBASED,
2NEXT_PARTPOINTER,
2FIRST_COMPONENTPOINTER,
2DESCRIPTION,
3PART_NUMBERPICTURE'X(5)9',
3COSTFIXEDDECIMAL(6,2);
DECLARE1GROUP(20)STATICLIKEASSEMBLY;
thentheseconddeclarationisequivalentto
DECLARE
1GROUP(20)STATIC,
2NEXT_PARTPOINTER,
2FIRST_COMPONENTPOINTER,
2DESCRIPTION,
3PART_NUMBERPICTURE'X(5)9',
3COSTFIXEDDECIMAL(6,2);
TheLIKEattributecausescopyingofmembersonly;attributes
attheleveloftheLIKEattributearenotcopied.Inthis
example,areferencetoGROUP(20).NEXT_PARTrequiresthatthe
qualifyingidentifierGROUPbeincluded,sinceotherwisethe
referencewouldbeambiguous.Thisbehaviorisageneral
propertyofstructuresdeclaredusingtheLIKEattribute.

42

EXPRESSIONS,TYPECONVERSION,ANDASSIGNMENT
ThekindsofexpressionsacceptableinPL/Iaresimilar
tothosefoundinmosthigherlevellanguages.Theseare:
literalconstants
referencestovariablesandnamedconstants
parenthesizedexpressions
functioncalls
prefixexpressions
infixexpressions
referencestobuiltinfunctions
Theonlykindsofliteralconstantsrecognizedarearithmetic
constantsandstringconstants.Otherconstantsareobtained
eitherasnamedconstants,e.g.,statementnames,orasthe
resultsofbuiltinfunctions,e.g.,NULL.Referencesto
variablesmayhavesubscripts,pointerqualifications(see
below),andnamequalifications.Anexampleofareference
withallthreeis
PT>X(I,J).B
Althoughthepointerqualifiersymbol>lookslikeanoperator
itisnottreatedasone(see"BasedStorage"below).
Parenthesesareusedwithinexpressionsinthreeways:
todesignatesubscriptsofarrays,todesignateargumentsof
functions,andtogroupcomponentsofexpressionscontaining
operators.Whenanexpressioncontainingoperators,e.g.,+
and*,isenclosedinparentheses,itistreatedasasingle

43

entitythisistheusualconventioninmathematicalnota
tion.Whenareferencetoavariableisenclosedinparen
theses,itisthentreatedasageneralexpressionrather
thanasavariable.Thisruleonlymakesadifferencein
thecontextofaprocedurecall.
Afunctioncallhastwoparts:thereferencetothe
functionandtheargumentlist.Thefunctionreferenceneed
nothavetheformofasingleidentifier,sincefunctions
canreturnentryvalues,canbesubscripted,andcanbe
membersofstructures.Functioncalls,subscriptedreferences,
andreferencestobuiltinfunctionsallhavethesamesyntactic
form,soaknowledgeoftherelevantdeclarationsisnecessary
inordertodistinguishthem.Anexampleofarathercomplex
functioncallis
A.B(3)(I,'NEXT')(X)
Inthiscase,A.B(3)isanelementofanarrayofstructures
(orastructureofarrays)containinganentryvalue.That
entryvaluedesignatesaprocedurethatexpectstwoarguments
inthiscase,Iandthestringconstant'NEXT'and
itselfreturnsanentryvalue.Theentryvalueobtainedfrom
thissecondprocedureisthenappliedtotheargumentX.A
functionexpectingnoargumentsiscalledbyusinganempty
argumentlist.Thus
NEXT_SUIT()
wouldcalltheprocedureNEXT_SUITwithnoarguments.
IfEisaprocedurethatitselfreturnsanentryvalue,then

44

F(E)
indicatesthatFistobecalledwithanargumentconsisting
oftheentryvalueassociatedwithE,while
F(E())
indicatesthatFistobecalledwithanargumentobtained
bycallingEasafunctionofnoarguments.Thisconvention
issomewhatdifferentfromtheoneusedinAlgol60andmany
ofitsdescendants.
Functioncallsarediscussedinmoredetailunder
"Procedures,ScopesandEnvironments"below.
PrefixandInfixExpressions
Aprefixexpressionconsistsofanexpressionprecededby
aprefixoperator,whileaninfixexpressionconsistsoftwo
expressionswithaninfixoperatorbetweenthem.Whenan
expressioncontainsastringofoperators,themeaningis
determinedbytheprecedencesoftheoperators.Thoseopera
torswithhighestprecedenceareappliedfirst,thenthoseof
nexthighestprecedence,etc.Theinfixoperators,grouped
byprecedencefromhightolow,are:
**
*/
+
||
==<><=>=<>
&
|

Table4summarizesthemeaningsoftheoperators.

45

Table4.PL/IOperatorsandTheirMeanings

InfixOperators
**

exponentiation

multiplication

division

addition

subtraction

||

concatenation

equal

notequal

<

lessthan

>

greaterthan

<=

lessthanorequal

>=

greaterthanorequal

<

notless

>

notgreater

PrefixOperators

minus

plus

not

46

Whenasequenceofadjacentoperators,allofthesameprece
dence,appears,theoperatorsareappliedfromlefttoright
exceptinthecaseof**,whichisappliedfromrighttoleft.
Thus
A*B/C**D**E
isinterpretedas
(A*B)/(C**(D**E))
Prefixoperatorsarealwaysappliedfirstunlesstheyconflict
withthe**operator;inthatcasethe**isappliedfirst,
sothat

A**3

isinterpretedas
(A**3)
eventhough
A*3
isinterpretedas
(A)*3
TherearefivearithmeticoperatorsinPL/I:
+addition
subtraction
*multiplication
/division
**exponentiation

Inordertoapplyanyofthefirstfour,theoperandsmust
firstbeconvertedtoacommonbase,scale,andmodeaccording
tothefollowingrules:

47

Base:

binaryifeitheroperandbinary,otherwisedecimal

Scale:

floatifeitheroperandfloat,otherwisefixed

Mode:

complexifeitheroperandcomplex,otherwisereal

Theoperandsneednothavethesameprecision,however.The
rulesfortheresultsoftheseoperationsassumethatthere
isamaximumvalueNforthenumberofdigitsoftheresult.
The"precisionrules"thengivethenumberofdigits(and,
forthecaseoffixed,thescalefactor)oftheresult.
Theyarearrangedsothatdigitsontherightarenever
thrownawayexceptinthecaseofdivision,whereitcannot
beavoided.Iftheoperandsarefloat,thenthenumberof
digitsoftheresultisthemaximumofthenumbersofdigits
oftheoperands.Otherwise,assumethatthetwooperands,
whicharenecessarilyfixed,haveprecision(p,q)and(r,s)
respectively.Theresultprecision(m,n)forthefouropera
tionsisgivenby:
+,

m=min(N,max(pq,rs)+max(q,s)+1)

n=max(q,s)
*

m=min(N,p+r+l)
n=q+s

m=N
n=Np+qs

Shouldtheresultvalueexceedthecapacityoftheresult
precision,theFIXEDOVERFLOWconditionisraised,indicating
anerror(see"ONUnitsandONStatements"below).
Thesituationwithregardtoexponentiationissomewhat
morecomplicated.Supposethattheformulax**yisbeing

48

computed.Ifeitherxoryisfloat,theresultisfloat,
andtheresultprecisionisthatofp.Ifxisrealand
fixed,andyisasmallintegerconstant,thentheresult
isalsorealandfixed,andtheprecisionoftheresult
isgivenby:
m=(p+1)*yl
n=q*y
Inanyothercasewherebothxandyarereal,theresultis
real.Ifeitherxoryiscomplex,theresultiscomplex.
Incertaincases,suchasxrealandfixedwithanegative
valueandynotaninteger,anerrorisindicated.
Thecomparisonoperatorsare:
=

equal

notequal

<

lessthan

>

greaterthan

<=

lessthanorequalto

>=

greaterthanorequalto

<

notlessthan

>

notgreaterthan

Theoperators<=and>areequivalent,asaretheoperators
>=and<;>and<areincludedmainlyforintellectual
compatibilitywithCOBOL,whichusesthephrasesNOTGREATER
andNOTLESS.Allofthecomparisonoperatorsreturna
onebitvalue:'1'Bifthecomparisonissatisfied,and'0'B
ifitisnot.Theequalityandinequalitycomparisonscanbe
appliedtoanytypeofdata,althoughformostofthenon
printabletypesbothoperandsmusthavethesametype.(The

49

onlyexceptionisthatpointerscanbecomparedtooffsets.)
Thecomparisonoperatorsthattestforinequalitycannot
beappliedtocomplexarithmeticdataortononprintabledata,
buttheycanbeappliedtorealarithmeticdata,topictured
data,andtostrings.Themeaningsoftheseoperators
appliedtoarithmeticdataaretheusualones;anumeric
pictureddatumistreatedasthenumericvaluethatitrepre
sents.Whencharacterstringsofunequallengtharecompared,
theshorteroneisfilledontherightwithblankstobringit
tothesamelengthasthelongerone.Theorderedcomparisons
arethendonelefttorightonthebasisoftheimplementation
definedcollatingsequence,whichdefinesanorderforthe
individualcharacters.Forinstance,thelettersareordered
alphabeticallyandthedigitsnumerically.Twocharacter
stringscompareequaliftheyareidenticalaftertheshorter
onehasbeenblankfilledontheright.Theabilityto
performorderedcomparisonsofcharacterstringsisparticu
larlyusefulinapplicationsthatinvolvesortingnames.
Similarrulesapplytobitstrings:Iftwobitstringsare
ofunequallength,theshorteroneisfilledontherightwith
zerobitspriortothecomparison.Ifthestringsdiffer,the
comparisonisdonebitbybitfromtheleftwiththerulethat
aonebitisgreaterthanazerobit.
Ifthetwooperandsofacomparisonhavedifferenttypes,
theyareconvertedtoacommontype.Ifonehasanarithmetic
type,theotherisconvertedtoanarithmetictype.Ifneither
hasanarithmetictype,butonehasacharactertypeandthe

50

otherhasabittype,thebittypeoperandisconvertedto
character.
Theconcatenationoperator,"||",isusedtoputtwo
stringstogether.Forinstance,thevalueof
'AVER'||'AGE'
isthestring'AVERAGE'.Ifoneoperandisabitstringand
theotherisacharacterstring,thebitstringisconverted
toacharacterstring(asitisforcomparisons).
Therearealsothreelogicaloperators:
&

and

or

not

'&'and"|"areinfixoperators,whileisaprefixoperator,
Theoperandsoftheseoperatorsareexpectedtobebitstrings,
sothatiftheyhaveanyothertype,theyareconvertedtobit
strings.
BuiltinFunctions
PL/Iincludesalargevarietyofbuiltinfunctions.Alist
ofthese,togetherwithabriefexplanationofwhateachone
does,isgiveninTable5.Someofthemoreimportantbuiltin
functionswillnowbedescribed.
Thefirstgroupofbuiltinfunctionsdealswithstrings.
Thedescriptionsofthefunctionswillbegivenforcharacter
strings,butthedefinitionsforbitstringsareanalogous.
ThebuiltinfunctionLENGTH(x)returnsasitsvaluethe

51

actuallengthofthecharacterstringx.Itisusefulin
twocontexts:determiningthelengthofastringpassedas
aparameter,anddeterminingthecurrentlengthofavarying
string.Inbothofthesecases,thedeclarationofthe
stringdoesnotprovideenoughinformationtodeterminethe
length.
ThebuiltinfunctionSUBSTR(x,y,z)isusedtoextracta
portionofastring.xisthestring,yisthepositionof
thefirstcharactertobeextracted,andzisthenumberof
characterstobeextracted.Ifzisomitted,allofthestring
startingwiththecharacteratpositiony.isextracted.The
nullstringisapossibleresult.SUBSTRcanalsobeused
ontheleftsideofanassignment.Forexample,giventhe
statements
DECLARECHAR8CHARACTER(8);
CHAR8='TOMJONES';
SUBSTR(CHAR8,2,5)='IMHA';
theresultingvalueofCHARSis'TIMHANES'.Abuiltinfunction
usedontheleftsideofanassignmentinthiswayiscalled
apseudovariable.
ThebuiltinfunctionINDEX(x,y)findsthefirstposition
withinthestringxwherethestringyoccurs.Ifydoesnot
occuratallwithinx,thevalueofINDEXis0.Forexample:

valueofINDEX('SYNCOPATION','COP')=4
valueofINDEX('SYNCOPATION','COPE')=0
ThebuiltinfunctionVERIFY(x,y)findsthefirstcharacterin

52

Table5.SUMMARYOFTHEPL/IBUILTINFUNCTIONS
Inthistable,descriptionsofthevariousPL/Ibuiltin
functionsaregiven.Thesedescriptionsareintendedto
indicatetheintentofeachfunction,andinsomecasesthe
principalrestrictionsontheirarguments.Inthedescriptions
ofthefunctions,squarebracketsareusedtoindicateoptional
arguments.
1.ABS(x)theabsolutevalueofx.Ifxiscomplex,
thevalueisitsmodulus.
2.ACOS(x)thearccosineofx.xmustnotbecomplex.
3.ADD(x,y,p,[q])thesumofxandywithprecision
(p,q)or(p,0)iftheresultisfixed,andwithprecision
(p)iftheresultisfloat.
4.ADDR(x)apointertothegenerationofx.
5.AFTER(sa,ca)theportionofthestringsathatfollows
thefirstoccurrenceofcawithinsa.Ifcadoesnot
occurwithinsa,thevalueisthenullstring.
6.ALLOCATION(x)thenumberofgenerationsofthecontrolled
variablexthatcurrentlyexist.
7.ASIN(x)thearcsineofx.xmustnotbecomplex.
8.ATAN(y[,x])thearctangentofy/xifxisgiven,
andofyotherwise.
9.ATAND(y[,x])thearctangentindegreesofy/xifxis
given,andofyotherwise.xandymustbereal.
10.ATANH(x)thehyperbolicarctangentofx.

53

Table5.Continued
11.BEFORE(sa,ca)theportionofthestringsathatprecedes
thefirstoccurrenceofcawithinsa.Ifcadoesnot
occurwithinsa,thevalueisthenullstring.
12.BINARY(x[,p[,q]])theresultofconvertingxtobinary,
withprecisiondeterminedbypandqifoneorbothisgiven.
13.BIT(x,[le])theresultofconvertingxtobit,with
lengthleifleisgiven.
14.BOOL(x,y,ca)thebooleanfunctionofxandywhosetruth
tableisspecifiedbythefourbitvalueca.
15.CEIL(x)theleastintegergreaterthanorequaltox.
xmustnotbecomplex.
16.CHARACTER(sa[,le])theresultofconvertingsatocharac
ter,withlengthleifleisgiven.
17.COLLATE()theimplementationdefinedcollatingsequence,
asacharacterstring.
18.COMPLEX(x,y)thecomplexnumberx+iy.
19.CONJG(x)thecomplexconjugateofx.
20.COPY(sa,le)thestringconsistingoflecopiesofsa
concatenatedtogether.
21.COS(x)thecosineofx.
22.COSD(x)thecosineofx,withxgivenindegrees.
xmustnotbecomplex.
23.COSH(x)thehyperboliccosineofx.
24.DATE()thecurrentdate,intheformyymmdd,where
yyistheyear,mmisthemonth,andddtheday.

54

25.DECAT(sa,ca,pa)aportionofthestringsa.sais
partitionedintothreepiecesbythefirstoccurrence
ofca.Thethreebitstringpaspecifieswhichofthe
threepieces(beforeca,caitself,afterca)aretobe
concatenatedtoformthevalueofDECAT.
26.DECIMAL(x[,p[,q]])theresultofconvertingxtodeci
mal,withprecisiondeterminedbypandqifoneorboth
isgiven.
27.DIMENSION(x,n)thenumberofelementsinthenth
dimensionofthearrayx,definedasHBOUND(x,n)
LBOUND(x,n)+1.
28.DIVIDE(x,y,p[,q])thequotientofxandywith
precision(p,q)or(p,0)iftheresultisfixed,and
withprecision(p)ifitisfloat.
29.DOT(x,y[,p[,q]])thedotproductofxandy,with
precisiondeterminedbypandqifoneorbothisgiven.
30.EMPTY()theemptyareavalue.
31.ERF(x)thestatisticalerrorfunctionofx.
32.ERFC(x)thecomplementofthestatisticalerrorfunc
tionofx.
33.EVERY(x)thevalue'1'Bifeverybitinxisaonebit,
and'0'Botherwise.Forthispurpose,allscalarelements
ofxareconvertedtobit.
34.EXP(x)theexponentialfunctionofx.
35.FIXED(x,p[,q])theresultofconvertingxtofixed,
withprecisiondeterminedbypand,ifitisgiven,q.
36.FLOAT(x,p)theresultofconvertingxtofloatwith
precision(p).

55

37.FLOOR(x)thegreatestintegerlessthanorequaltox.
xmustbereal.
38.HBOUND(x,n)theupperboundofthenthdimensionof
thearrayx.
39.HIGH(le)astringoflecopiesofthehighestcharacter
inthecollatingsequence.
40.IMAG(x)theimaginarypartofthecomplexnumberx.
41.INDEX(sa,ca)thepositionwithinthestringsaofthe
firstoccurrenceofthestringca.Thevalueis0ifca
doesnotoccurwithinsa.
42.LBOUND(x,n)thelowerboundofthenthsubscriptof
thearrayx.
43.LENGTH(sa)thelengthofthestringsa.
44.LINENO(fn)thecurrentlinenumber(withinapage)of
theprintfilefn.
45.LOG(x)thenaturallogarithmofx.
46.LOG10(x)thelogarithmtothebase10ofx.xmust
notbecomplex.
47.LOG2(x)thelogarithmtothebase2ofx.xmustnot
becomplex.
48.LOW(le)astringoflecopiesofthelowestcharacter
inthecollatingsequence.
49.MAX(x1,x2,...,xn)thelargestofthenumericalvalues
ofthexi.Thexi.mustnotbecomplex.
50.

MIN(x1,x2,...,xn)thesmallestofthenumericalvalues
ofthexi.Theximustnotbecomplex.

51.

MOD(x,y)thevalueofxmoduloy.xandymustnotbe
complex.
56

52.

MULTIPLY(x,y,p[,q])theproductofxandywithpreci

sion(p,q)or(p,0)iftheresultisfixed,andwith
precision(p)ifitisfloat.
53.NULL()thenullpointer.
54.OFFSET(pt,ar)theresultofconvertingthepointer
pttoanoffsetwithintheareaar.
55.ONCHAR()theleftmosterroneouscharacterwithinthe
currentONSOURCEvalue.Whentheconversioncondition
israised,thecurrentONSOURCEvalueissettothestring
whoseconversionwasbeingattempted,anditretainsthis
valueduringtheexecutionoftheassociatedonunit.
56.ONCODE()animplementationdefinedintegerindicating
thenatureoftheonconditionassociatedwiththecurrent
onunit.
57.ONFIELD()thecontentsofanerroneousfieldencountered
duringdatadirectinput,causingthenameconditiontobe
raised.
58.ONFILE()thenameofthefilebeingprocessedwhenan
inputoutputconditionwasraised.
59.ONKEY()thenameofanerroneouskeythatcausedthe
KEYconditiontoberaisedduringrecordinputoutput.
60.ONLOC()thenameoftheprocedureentrypointactive
whenthecurrentonunitwasraised.
61.ONSOURCE()thecurrentonsourcevalue.WhentheCONVER
SIONconditionisraised,thecurrentONSOURCEvalueis
settothestringwhoseconversionwasbeingattempted,
62.PAGENO(fn)thenumberofthecurrentpagewithinthe
printfilefn.

57

63.POINTER(ofe,ar)theresultofconvertingtheoffset
ofewithintheareaartoapointer.
64.PRECISION(x,p[,q])theresultofconvertingxto
precision(p,q)or(p,0)ifxisfixed,andtoprecision
(p)ifxisfloat.
65.PROD(x)theproductofalltheelementsofthearrayx.
66.REAL(x)therealpartofthecomplexnumberx.
67.REVERSE(sa)thebitsorcharactersofthestringsa
takeninreverseorder.
68.ROUND(x,n)theresultofroundingupthenumericalvalue
ofx.Ifxisfixed,theresulthasascalefactorofn;
otherwisetheresulthasanumberofdigitsofn.
nmustbeanintegerconstant.
69.SIGN(x)thevalue+1,0,or1accordingtowhetherxis
positive,zeroornegative.
70.SIN(x)thesineofx.
71.SIND(x)thesineofx,withxgivenindegrees.
xmustnotbecomplex.
72.SINH(x)thehyperbolicsineofx.
73.SOME(x)thevalue'1'Bifatleastonebitinxisa
onebit,and'0'Botherwise.Forthispurpose,all
scalarelementsofxareconvertedtobit.
74.SQRT(x)thesquarerootofx.
75.STRING(sa)theresultofconcatenatingtogetherthe
scalarelementsofsaafterconvertingthemtobit.
76.SUBSTR(sa,st[,le])thesubstringofsaconsistingofle
charactersorbitsofsabeginningwiththestthone.

58

Table5.Continued
Ifleisomitted,thesubstringconsistsofthe
charactersorbitsfromthestthonetothelast.
77.SUBTRACT(x,y,p[,q])thedifferenceofxandywith
precision(p,q)or(p,0)iftheresultisfixed,and
withprecision(p)ifitisfloat.
78.SUM(x)thesumofalltheelementsofthearrayx.
79.TAN(x)thetangentofx.
80.TAND(x)thetangentofx,withxgivenindegrees.
xmustnotbecomplex.
81.TANH(x)thehyperbolictangentofx.
82.TIME()thecurrenttime,intheformhhmmsswhere
hhgivesthehour,mmgivestheminute,andss...sgives
thesecondcarriedtoanimplementationdefinednumberof
fractionaldecimalplaces.
83.TRANSLATE(sa,ra[,pa])theresultofreplacing,within
sa,eachcharacterofpabythecorrespondingcharacter
ofra.Ifpaisomitted,itistakentobethecollating
sequence.
84.TRUNC(x)theresultoftruncatingxtothenearestinteger
inthedirectionofzero.xmustnotbecomplex.
85.UNSPEC(x)theinternalrepresentationofx,asabitstring
86.VALID(sa)thevalue'1'Bifthecurrentvalueofthe
picturedvariablesaconformstothepictureand'0'B
otherwise.
87.VERIFY(sa,ca)thepositionwithinthestringsaofthe
firstcharacterorbitofsathatdoesnotappearwithinca.
cathusbehavesasasetratherthanasequence.Ifall
charactersorbitsofsaoccurwithinca,thevalueofVERIFY
is0.

59

thestringxthatisnotacharacterofthestringy.Ifall
thecharactersofxappeariny,thenthevalueofVERIFYis0.
Forexample:
valueofVERIFY('CABDRIVER','ABCDE')=5
valueofVERIFY('CEDE','ABCDE')=0
ThebuiltinfunctionREVERSE(x)reversesitsargument,sofor
example:
valueofREVERSE('GALLOP')='POLLAG'
Thisfunctionisusefulinrighttoleftscanning;thestring
tobescannedisreversedandthenscannedlefttoright.The
builtinfunctionCOLLATE()(the"()"indicatesthatCOLLATE
isafunctionofnoarguments)hasasitsvaluetheimplemen
tationdefinedcollatingsequence,i.e.,thestringconsisting
ofallacceptablecharactersorderedfromleasttogreatest.
ThebuiltinfunctionCOPY(x,n)createsncopiesofthestringx.
Forexample,
valueofCOPY('CHA',3)='CHACHACHA'
Thearithmeticbuiltinfunctionsenabletheusertocontrol
theattributesofarithmeticresults.Thesefallintotwo
groups.First,therearebuiltinfunctionsADD,SUBTRACT,
MULTIPLY,andDIVIDEthatbehavelikethecorrespondinginfix
operators,exceptthattheprecisionoftheresultisexplicitly
specified.Forexample,
MULTIPLY(Ml,M2,5,3)
producesaresultwhoseprecisionis(5,3),andwhoseremaining
attributesaredeterminedbytheattributesofMlandM2.

60

Second,therearebuiltinfunctionsFIXED,FLOAT,BINARY,and
DECIMALthatconverttheirargumenttothespecifiedattribute
withthespecifiedprecision.Forinstance,
DECIMAL(M1,4,2)
convertsMltofixeddecimalwithprecision(4,2);themodeof
theresultisthemodeofMl.
TheconversionbuiltinfunctionsFIXED,FLOAT,BINARY,and
DECIMALcanbeusednotonlytoconvertamongarithmetictypes
butalsotoconvertfromthestringtypes.Therulesforthe
conversionarediscussedunder"TypeConversion"below.There
arefurtherconversionfunctionsREAL(x)whichconvertsxto
realtype(andforacomplexnumber,takesitsrealpart);
IMAG(x),whichtakestheimaginarypartofthecomplexnumber
x(andyieldsifxisnotacomplexnumber);andCOMPLEX(x,y),
whichconvertsxandytoacommonrealtypeandthenforms
thecomplexnumberx+iy.Forconversiontostringtypes,the
builtinfunctionsCHARACTER(x,n)andBIT(x,n)canbeused.
CHARACTER(x,n)firstconvertsxtocharactertypeandthen
adjuststhelengthoftheresulttoneitherbytruncatingon
therightorbyfillingontherightwithblanks.BITbehaves
similarly,eithertruncatingorfillingwithzerobits.The
secondargumentofeitherofthesefunctionsmaybeomitted,
inwhichcasenotruncationorfillingisdone.
ThemathematicalbuiltinfunctionsincludedinPL/Iare
listedinTable6.Withtheexceptionsindicated,theycan
acceptargumentsofanyarithmetictype,includingcomplex
types.Forsomemathematicalfunctionsthereismorethanone

61

possiblerangefortheresultvalue,andthechoiceofprincipal
valueisspecifiedinthetable.
ThefunctionATAN(arctangent)canaccepteitheroneor
twoarguments.Thetwoargumentversionisusefulinconverting
rectangularcoordinatestopolarcoordinates.Iftherectangular
coordinatesaregivenbythepair(x,y),thenATAN(x,y)gives
thecorrespondingpolarangleintherangefromto+.Since
thevalueofthetangentfunctionrepeatsevery/2radians,
thesignofyisneededtodeterminethecorrectvalue.
Anumberofthebuiltinfunctionsfallintonoparticular
category.ThebuiltinfunctionSUM(x)acceptsanarrayas
argument,andreturnsasvaluethesumofalltheelementsof
thearray.ThebuiltinfunctionPROD,for"product",behaves
similarly.ThebuiltinfunctionDOT(x,y)expectsitsarguments
tobeonedimensionalarraysbothhavingthesamebounds;
ittakesthemathematicaldotproductofxandy.Thebuiltin
functionBOOL(x,y,z)takesasargumentstwobitstringsxand
yofarbitrarylength,andathirdbitstringzoflength4.
zdeterminesabooleanfunctionthatisappliedtoxandy.
Ifzisthesequenceb1b2b3b4,thenthefunctionisdefined
by:
bitofx

bitofy

result

b1

b2

b3

b4

62

Table6.MathematicalBuiltinFunctions
PL/I
Name

Mathematical
Description

Complex
Arguments?

Constraintson
ResultR
(PrincipalValue)

ABS

absolutevalue

yes

R0

ACOS

arccosine

no

0R

ASIN

arcsine

no

/2R/2

ATAN1

arctangent(oneargument) yes

/2<R</2
(realargument)

ATAN2

arctangentofquotient
(twoarguments)

<Re(R)<
(complexargument)

ATAND1

arctangentofquotient
indegrees(oneargument)

no

90<R90

ATAND2

arctangentofquotient
indegrees(2arguments)

no

180<R180

ATANH

hyperbolicarctangent

yes

COS

cosine

yes

COSD

cosineindegrees

no

COSH

hyperboliccosine

yes

ERF

errorfunction

no

ERFC

complementoferrorfunc
tion

no

EXP

exponential

yes

LOG

naturallogarithm

yes

LOG2

Base2logarithm

no

LOG10

base10logarithm

no

SIN

sine

yes

SIND

sineindegrees

no

SINH

hyperbolicsine

yes

SQRT

squareroot

yes

TAN

tangent

yes

TAND

tangentindegrees

no

TANH

hyperbolictangent

yes

63

<Im(R)

Re(R)>0or
Re(R)=0andIm(R)0

ThebuiltinfunctionVALIDcanbeusedtocheckthe
validityofpictureddata,i.e.,toensurethatthevalue
storedinapicturedvariablefitsthedescriptiongivenby
thepicture.VALID(x)returns'1'Bifthepicturedvariable
xcontainsavalidvalue,and'0'Botherwise.Invalidvalues
canarisesinceanarbitrarycharacterstringcanberead
intoorassignedtoapicturedvariable,andordinarilyno
validitycheckismadeatthetimeofreadingorassignment.
ThebuiltinfunctionsEVERYandSOMEareusefulin
testingpropertiesofaggregates.EVERY(x)returns'1'Bif
itsargument(afterconversiontobittype,ifnecessary)
consistsentirelyofonebits,and'0'Botherwise.SOME(x),
ontheotherhand,returns'1'Bifitsargumentcontainsat
leastoneonebit,and'0'Botherwise.Forexample,ifAis
anarrayofarithmetictype,thentheexpressionA>0will
beanarraywithaonebitineachpositioniwhereA(i)>0.
ThereforeEVERY(A>0)willreturn'1'BifallelementsofA
aregreaterthan0,whileSOME(A>0)willreturn'1'Bifat
leastoneelementofAisgreaterthan0.
TypeConversion
InPL/Iitispossibletoconvertfromanyprintable
typetoanyother,althoughforcertainvaluestheconversion
maybeillegal.Conversionsmaybeinvokedeitherexplicitly,
usingbuiltinfunctionssuchasFLOATorCHARACTER,or
implicitlyincontextssuchasoperandsofoperatorsor
argumentsoffunctions.Forinstance,theconcatenation

64

operatorrequiresthatitsoperandsbestringsofthesametype
(bitorcharacter),sothattheoperandsmustbeconverted
appropriatelyeveniftheyareofarithmetictype.The
textofaproceduredefinesthetypesofitsparameters,and
iftheargumentsofaproceduredonotalreadyhavetheexpect
edtypes,theytoomustbeconverted.Infact,PL/Iprovides
implicitconversionsinalmosteverycontextwhereconversion
ispossible.
Theconversionsamongarithmetictypesgenerallyfollow
theprincipleofpreservingthemeaningoftheconverted
value.Forexample,theresultofconvertingthefixedvalue
7.3tocomplexfloatdecimalwithprecision(8)is
.73000000E+01+0I.Inconversiontoafixedtypewhendigits
mustbedropped,theresultvalueisobtainedbytruncating
towards0,althoughincertainunusualcasesanimplementation
mayproduceaslightlydifferentresult.Whenconverting
fromrealtocomplexanimaginarypart0ofisadded,while
whenconvertingfromcomplextorealtheimaginarypartis
dropped.
Theconversionbetweenbitandcharacterisstraightfor
ward;zerobitscorrespondtothecharacter"0",andonebits
correspondtothecharacter"1".Acharacterstringtobe
convertedtobittypemustconsistentirelyofthesetwo
characters,oranerrorissignalledspecifically,the
CONVERSIONcondition.Itispossiblefortheprogrammerto
modifytheconvertedvaluesoastocorrecttheerror(see
"CategorizationoftheONConditions"below).

65

Themostcomplicatedconversionsarethosebetweenthe
stringtypesandthearithmetictypes.Acharacterstringis
convertedtoanumberbytreatingthestringastherepresen
tationofanumber.Thus,giventhestatements
DECLARENUMVFIXEDDECIMAL(5,2);
NUMV='2.13E1';
thestring'2.13E1'isconvertedfirsttothefloatvalue
thatitrepresents,andthentothefixeddecimalvalue21.30.
Theblankssurroundingthenumberarealwayspermissible.
Anallblankvalueconvertstozero.Ifthecharacterstring
doesnotrepresentavalidnumber,thentheCONVERSIONcondi
tionissignalled.Asinthecaseofconversionfromcharacter
tobit,itispossiblefortheprogrammertocorrecttheerror.
Conversionfromanumbertoacharacterstringyields,
ineffect,theresultofprintingthenumber.Ordinarilythat
resultincludesleadingblanks.Forinstance,theeffectof
DECLARENUMVFIXEDDECIMAL(4);
DECLARECONV_RESULTCHARACTER(20)VARYING;
NUMV=17;
CONV_RESULT=NUMV;
istoassignthestring'17'toNUMV.Inmostcasesthe
lengthoftheresultingstringisthenumberofdigitsafter
conversion(ifnecessary)tofixeddecimal,plusthree.
Threesparepositionsareneededinordertoaccommodatea
possiblesign,apossibledecimalpoint,andapossibleleading
zero.

66

Conversionfromanarithmeticvaluetoabitstringis
accomplishedbyfirstconvertingthearithmeticvaluetoreal
fixedbinaryandthenconvertingtheintegerpartofthe
valuetothecorrespondingbitstring.Forinstance,convert
ingthevalue12.6toabitstringyields'00ll00'B,withan
intermediateconversionfromfixeddecimalwithprecision
(3,1)tofixedbinarywithprecision(10,4),(Therulesfor
obtainingtheintermediateprecisionaresomewhatcomplicated,
butitcanbeseenthattwodigitstotheleftofthedecimal
pointmayrequireasmanyassixnonzerobitstorepresent
theirvalue.)Conversionfromabitstringtoanarithmetic
typeisaccomplishedbytreatingthebitstringasabinary
number,andthenconvertingfromthatnumbertothedesired
type.
Itisalsopossibletoconvertfrompointertooffset,
orviceversa,providedthatanareaisgiven.ThusifAR
isanareaandPisapointer,theexpressionOFFSET(P,AR)
givestheresultofconvertingPtoanoffsetrelativetoAR.
Similarly,ifOFSisanoffset,POINTER(OFS,A)givesthe
resultofconvertingOFStoapointerrelativetoA.Apointer
canbedeclaredwithanareareference,asin
DECLAREAR2AREA;
DECLAREO2OFFSET(AR2);
Inthiscase,O2canimplicitlybeconvertedtoapointer,
andtheareaAR2isusedintheconversion.

67

Promotion
ThePL/Ioperators,andmanyofthebuiltinfunctions
also,canbeappliedtoaggregatesaswellastoscalars.When
twoaggregatesofthesameorganization,i.e.,twostructures
withequalnumbersofcomponentsortwoarraysofthesame
dimensionality,areusedastheoperandsofanoperator,the
resultalsohasthatorganization,andtheresultisformed
bycombiningcorrespondingcomponentsoftheoperands.
Forexample,in
DECLAREA(3,4)FIXEDBINARY;
DECLAREB(3,4)FIXEDBINARY;
DECLAREC(3,4)FIXEDBINARY;
A=B+C;
theassignmenttoAisaccomplishedbyaddingB(l,l)toC(1,1),
B(l,2)toC(l,2),etc.,toformanewarrayofsumswith
dimensionality(3,4).ThearrayofsumsisthencopiedintoA.
Incertainpeculiarcasesthetemporaryarraycontainingthe
sumisactuallyneeded,anditdoesnotsufficesimplytoadd
theelementsofBandConebyoneandplacetheresultdirectly
inA.
Itisalsopossibletocombinescalarswithstructures,
scalarswitharrays,andstructureswitharrays.However,it
isnotpossibletocombinestructureshavingdifferentnumbers
ofmembers,orarrayshavingdifferentdimensionalities.A
scalariscombinedwithastructurebypromotingittoa
similarstructure,allofwhosemembershavethesamevalueas
thescalar.Similarly,ascalariscombinedwithanarrayby

68

promotingthescalartoasimilararray.Thecaseofcombin
ingastructurewithanarrayismorecomplicated;firstthe
originalstructureispromotedtoanarrayofstructures,and
latereachelementoftheoriginalarrayispromotedtoa
structure.Asimpleinstanceofpromotionisgivenbythe
expressionA+1,whereAisanarrayofarithmetictype.The
valueofthisexpressionisobtainedbycreatinganarrayof
1's,havingthesamedimensionalityasA,andthenadding
thisnewarraytoA,elementbyelement.Theeffectisjust
thesameasadding1toeachelementofA.
TheAssignmentStatement
Theassignmentstatementcontainsaleftside,whichis
alistoftargets,andarightside,whichisanexpression.
Eachofthetargetsdesignatesalocationcapableofreceiving
avalue.Thestatementisexecutedbyevaluatingtheexpres
sionandthenstoringitsvalue,afterappropriateconversion,
intothelocationdesignatedbyeachtarget,inorderfrom
lefttoright.Forinstance,theassignmentstatement
A,B(I),C=l;
causes1tobestoredintoA,B(I),andC.Thetargetsof
anassignmentstatementmaybevariablesorpseudovariables.
Forinstance,theassignmentstatement
SUBSTR(TEXT,I,LEN)=WORD;
storesthevalueofWORDintotheindicatedsubstringofTEXT
(afteradjustingthesizeofthevaluetobeLEN).Similarly,

69

IMAG(Z)=SIN(X);
causestheimaginarypartofthe(necessarily)complexvari
ableZtobesettothevalueofSIN(X),whiletherealpart
ofZisleftundisturbed.
Sincethetypeofthevalueobtainedfromtherightside
ofanassignmentstatementmaydisagreewiththetypeofa
target,promotionorconversion,orboth,maybenecessary.
Ifthetargetisascalar,thentheusualrulesforscalar
conversionareapplied;thetypeofthetargetdefinesthe
typetowhichthevaluemustbeconverted.

Ifthetargetis

astructureorarray,thenthevaluemustbepromotedtothe
typeofthatstructureorarray,byreplicatingelementsas
necessary.

Followingthepromotion,elementbyelementscalar

conversionmaybenecessary.Forinstance,intheexample
DECLAREHVAR(30)FLOATBINARY;
HVAR=0;
thescalarvalueispromotedtoanarrayof30fixedzeros.
Eachoftheseisthenconvertedtoanappropriatefloatzero,
andassignedtothecorrespondingelementofthearray.*
Avariationontheassignmentstatement,called
bynameassignment,canbeusedtoassignelementsfromone
structuretoanotheraccordingtothenamesoftheelements
ratherthanaccordingtotheirpositionsinthestructure.
Forinstance,giventhedeclarations

*Inactualpractice,theconversionisusuallydonebefore
ratherthanafterthepromotion.Theresultisthesame.

70

DECLARE
1

DECLARE
1

RED,
2
BLUE,
2
GREEN,
3
ORANGE,
3
WHITE,
2
BLACK,
2
GRAY;
VIOLET,
2BLACK,
2WHITE,
2GREEN,
3
ORANGE,
3
VIOLET,
2TAN,
2BLUE;

theeffectoftheassignmentstatement
RED=VIOLET,BYNAME;
istoperformtheindividualassignments
RED.BLUE=VIOLET.BLUE;
RED.GREEN.ORANGE=VIOLET.GREEN.ORANGE;
RED.BLACK=VIOLET.BLACK;
Thosemembersnotincommonbetweenthetwostructuresare
ignored.Bynameassignmentcanbeextendedtoaccommodate
expressionsthatinvolvestructures.

71

STORAGETYPES
PL/Iprovidesavarietyofwaystomanagethestorage
ofvariables.Eachvariablehasastoragetype,whichcan
beeitherparameter,defined,orastorageclass.Theparameter
anddefinedstoragetypesindicatethatthevariableisan
alias,i.e.,analternatename,forstoragethathasalready
beenobtainedbyothermeans.Thestorageclassesprovide
differentwaysofallocatingandfreeingstorage;thestorage
classesarestatic,automatic,controlled,andbased.The
storagetypeofavariableisdeterminedbyitsdeclaration
afteralldefaultingofdeclarationshasbeendone;inmost
casesthedefaultistheautomatictype.Thestorageused
toholdthevalueofavariableiscalledageneration.A
generationcanexisteventhoughitisnotcurrentlyassociated
withanyvariable.

StaticStorage
Thestaticstorageclassisthesimplestone.Whena
variableisdeclaredtobestatic,itsgenerationisallocated
atthestartofprogramexecutionandremainsallocated
throughoutprogramexecution.Whenastaticvariableis
declaredwithinaprocedure,thevaluesofthatvariableare
keptfromonecalloftheproceduretothenext.Eveninthe
caseofarecursiveprocedure,thereisjustonecopyofthe
variable,andthatcopyisavailableatalllevelsofrecur
sion.Staticstorageismuchlikethestandardformofstorage
inFORTRAN.

72

AutomaticStorage
Storageforanautomaticvariableisallocatedonentrance
totheblockwherethevariableisdeclared,andfreedonexit
fromthatblock.Whenevertheblockisentered,afreshgener
ationisobtainedforthevariable.Inpracticeitsometimes
happensthatvaluesofautomaticvariablesareretainedfrom
oneblockentrancetothenext,butthisbehaviorisnotany
thingthattheprogrammercanrelyupon.Whenanautomatic
variableisdeclaredwithinarecursiveprocedure,anew
generationiscreatedforeachlevelofrecursion,andremains
associatedwiththevariableatthatrecursionleveluntil
therecursionlevelisterminated.Automaticstorageresembles
theordinarylocalstorageofAlgol.

ControlledStorage
Controlledstorageisexplicitlyallocatedandfreedby
theprogrammerusingtheALLOCATEstatementandtheFREEstate
ment.Eachtimethevariableisallocated,anewgeneration
foritiscreatedandplacedonapushdownstack;eachtimethe
variableisfreed,thegenerationatthetopofthestackis
destroyed.Thereisonesuchstackforeachcontrolledvariable,
andthecurrentvalueofthevariableisalwaysobtainedfrom
thegenerationatthetopofthestack.Inotherwords,the
generationsfollowalastinfirstoutrule.
Thevaluesofstringlengthsandarraydimensionsinthe
declarationofacontrolledvariablecanbegivenbyexpressions.

73

Theexpressionsareevaluatedwhenanewgenerationisallocated,
andsothedifferentgenerationsneednotallhavethesame
sizes.Forexample,supposethatwearegiventhestatements:
DECLARENFIXED;
DECLARECONTVCHARACTER(N)CONTROLLED;
N=5;
ALLOCATECONTV;
CONTV='FIRST';
N=7;
ALLOCATECONTV;
CONTV='SECOND';
IfCONTVhasnotbeenpreviouslyallocated,thesestatements
willcreateastackconsistingoftwogenerations.Thegenera
tionatthetopofthestackwillhavelength7andvalue
'SECOND'(theassignmentaddsablankontheright),while
theothergenerationwillhavelength5andvalue'FIRST'.
ThusthecurrentvalueofCONTVwillbe'SECOND'.Ifthe
statements
FREECONTV;
PUTLIST(CONTV);
areexecuted,thenthegenerationatthetopofthestackwill
bedestroyedandCONTVwillrefertothefirstgeneration.
ConsequentlythePUTstatementwillcauseFIRSTtobeprinted.

BasedStorage
Basedvariablesareusefulincreatinglinkeddatastruc
tures,andalsohaveapplicationsinrecordinputoutput.A
basedvariabledoesnothaveanystorageofitsown;instead,
thedeclarationactsasatemplateanddescribesageneration
ofstorage.Inordertousethevariabletorefertoa

74

particulargenerationofstorage,apointertothatgeneration
mustalsobeprovided.Thepointerandthebasedvariable,
takentogether,constituteabasedreference.Inmanycases,
thepointerisgivenimplicitlyratherthanexplicitly.
Anexampleofadeclarationofabasedvariableanda
pointeris
DECLARE
1

ARRAY_ELTBASED,
2ARRAY(10)FLOAT,
2NEXT_ELTPOINTER;
DECLAREAPPOINTER;
ARRAY_ELTdescribesagenerationofstorage,namely,astruc
turecontainingafloatarrayandapointer.Thebased
reference
A>ARRAY(4)
designatesaparticularelementwithintheARRAY_ELTstructure
pointedatbythepointerAP,andifAPdoesnotpointatsuch
astructurethereferenceisinvalid.PL/Idoesnotprovide
anymechanismforcheckingthatapointerisindeedpointing
atagenerationofthecorrecttype,andsoitisentirelythe
programmer'sresponsibility.Theerrorsthatresultwhena
pointerpointsatanobjectofthewrongtypecanoftenbe
extremelydifficulttotrackdown.
Thestatement
ALLOCATEARRAY_ELTSET(AP);
causesagenerationmatchingthetypeofARRAY_ELTtobe
createdandalsocausesthepointerAPtopointatthatgenera
tion.Thus,afterthisALLOCATEstatementhasbeenexecuted,

75

areferencetoAP>ARRAY(4)willbevalid.Ifsubsequently
thestatement
FREEAP>ARRAY_ELT;
isexecuted(andthevalueofAPhasnotbeenchangedinthe
meantime),thegenerationpointedatbyAPwillbedestroyed,
andsubsequentreferencestothatgenerationwillbemeaning
less.
Inthisexample,thestructureincludesnotonlythe
arraybutalsoapointer.Thatpointercanbeusedtoform
alistofarrays,eachonepointingtoitssuccessor.An
elementisaddedtotheheadofthelistbyallocatingit
andsettingitsNEXT_ELTcomponenttothepreviouslisthead.
Similarly,theheadofthelistisdeletedbysettingthe
newlistheadtotheNEXT_ELTcomponentoftheoldlisthead
andthenfreeingtheoldlisthead.Oneofthemainuses
ofbasedvariablesandpointersinPL/Iisconstructinglists
suchasthisone.Inordertoendalist,aspecialnull
pointerisneeded,andthatpointerisprovidedbytheNULL
builtinfunction.
Itisinconvenienttohavetowriteapointerwithevery
basedreference.Thereforeitispossibletodeclarean
implicitpointerinthedeclarationofabasedvariable,e.g.,
DECLAREBFIXBASED(BFP)FIXED;
DECLAREBFPPOINTER;
AreferencetoBFIXbyitselfistakentomeanBFP>BFIX.
Moreover,thestatement

76

LOCATEBFIX;
isequivalentto
ALLOCATEBFIXSET(BFP);
andthestatement
FREEBFIX;
isequivalentto
FREEBFP>BFIX;
Thetemplategivenbyabasedvariablecanbeappliedto
storageoftypesotherthanbased.Inordertoobtainapointer
toageneration,theADDRbuiltinfunctionisused.ADDR(v)
yieldsapointertothegenerationspecifiedbyv.Asan
example,thestatements
DECLAREBCOMPFLOATCOMPLEXBASED;
DECLARESCOMPFLOATCOMPLEXSTATIC;
ADDR(SCOMP)>BCOMP=2E0+3E0I;
causethestaticvariableSCOMPtobesettothevalue2E0+3E0I.

TheReferOption
Thestringlengthsandarrayboundsofabasedvariable
canbespecifiedbyexpressionsaswellasbyconstants.For
example,thedeclaration
DECLAREBCSCHARACTER(M)BASED;
indicatesthatthelengthofBCSisgivenbythecurrentvalue
ofM.WhenBCSisallocated,thegenerationthatiscreated
willhavealengthgivenbythecurrentvalueofM,andwhen
referenceismadetoBCS,thevalueofMmustagreewiththe

77

lengthofthestringinthegenerationreferredto.Ifa
numberofgenerations,allcorrespondingtoBCS,exist,it
maybedifficulttoensurethatthecurrentvalueofMis
correct,sincethegenerationsmayhavedifferentstring
lengths.Inordertodealwiththisdifficulty,PL/Iallows
thestringlengthtobespecifiedalongwiththestring
itself;boththestringandthelengtharestoredinasingle
structure,sometimescalledaselfdefiningstructure.For
instance,thestructure
DECLARE
1STRING_STRUCBASED(STP),
2LENFIXED,
2NEXTPOINTER,
2STRINGCHARACTER(LEN1REFER(LEN));
DECLARESTPPOINTER;
couldbeusedtocreatealistofstrings,eachhavinga
differentlength.Whenoneofthesestructuresisallocated,
thelengthofthestringisobtainedasthecurrentvalueof
LENl,andatthesametimethecurrentvalueofLENlisauto
maticallystoredwithintheLENcomponentofthenewlycreated
generation.Whenoneofthesestructuresisreferenced,the
lengthofSTRINGisobtainedfromtheLENcomponentofthat
structure.BothLENandLENlareneeded,forthefollowing
reason.WereLENusedwithoutthesocalledreferoption,
theallocationsizewouldbetakenfromSTP>LENpriortothe
allocation,whichwouldbeeitherundefinedorthestring
lengthofapreviouslyallocatedgeneration.Ontheother
hand,wereLENlused,itwouldthenbenecessarytoresetit
toLENbeforereferencingSTRING,sinceotherwisethelength

78

ofSTRINGwouldnotbecorrect.
Abasedvariablemaycontainanynumberofreferoptions.
Thesecanbeusedtospecifyupperorlowerarrayboundsas
wellasstringlengthsandareasizes.
LefttoRightCorrespondence
Itisoftennecessarytocreatedatastructuresinwhich
theelementsdonotallhavethesametype,asinthefollowing
example:
DECLARE
1FLOAT_ELEMENTBASED(ELPTR),
2ELTYPEFIXED,/*1FORFLOAT*/
2NEXTPOINTER,
2VALUEFLOAT;
DECLARE
1FIXED_ELEMENTBASED(ELPTR),
2ELTYPEFIXED,/*2FORFIXED*/
2NEXTPOINTER,
2VALUEFIXED;

DECLARE
1CHAR_ELEMENTBASED(ELPTR),
2ELTYPEFIXED,/*3FORCHARACTER*/
2NEXTPOINTER,
2VALUECHARACTER(24);

DECLAREELPTRPOINTER;

Alistcanbeformedcontainingelementsofallthreekinds,
storingatypecodeinELTYPEinordertodistinguishamong
them.Inordertoreferenceanelement,itisnecessaryto
specifyeitherFLOAT_ELEMENT,FIXED_ELEMENT,orCHAR_ELEMENT
evenbeforethetypeoftheelementisknown,sincearefer
encetoELTYPEbyitselfissyntacticallyambiguous.Therefore
undercertainconditionsPL/Iallowsareferencetoacomponent

79

ofabasedstructureevenwhenthevariableinthereference
doesnotagreewiththegenerationbeingreferenced.The
primaryconditionisthatthegenerationandthevariablemust
agreeuptothatcomponent,althoughtherearefurtherdetailed
requirementsthatarebeyondthescopeofthisarticle.Based
referencessatisfyingthisconstraintaresaidtobein
lefttorightcorrespondence,sincetheyagreereadingfrom
lefttoright.Thusitispermissibletouse
FLOAT_ELEMENT.ELTYPEtoreferto,andthereforetotest,the
typecodestoredinanyoneofthethreekindsofelements.
EvenifELPTRispointingatagenerationhavingthetypeof
CHAR_ELEMENT,theELTYPEcomponentofthatgenerationcanbe
referencedusingFLOAT_ELEMENT.ELTYPE.SinceELTYPEisthe
firstcomponentofeachelement,theelementsnecessarily
agreeuptothatcomponent.Moreover,theNEXTcomponentsof
thethreekindsofelementscanbereferencedinterchangeably
sinceineachkindofelementNEXThastypepointerandis
precededbyanelementhavingtypefixed(withtheremaining
attributesdefaultedidenticallyinallcases).

AllocationinAreas
Abasedvariablecanbeallocatedinaspecifiedarea,
asinthefollowingexample:
DECLAREBVFIXEDBASED(P);
DECLAREAAREA(200);
ALLOCATEBVIN(A);
SinceBVhasbeenallocatedinA,theOFFSETbuiltinfunction

80

canbeusedtoconvertPintoanoffsetrelativetoA,as
givenby
OFFSET(P,A)
Theallocationcanassignavaluedirectlytoanoffset
variable,asintheexample
DECLAREOFSOFFSET(A);
DECLAREBVlBASED(OFS);
ALLOCATEBVlIN(A);
SinceBVlisbasedonOFS,theoffsetofBVlrelativetoAis
assignedtoOFSwhentheALLOCATEstatementisexecuted.
ParameterStorage
Avariableacquirestheparameterstoragetypebyvirtue
ofitsappearanceinaparameterlistofeitheraPROCEDURE
statementoranENTRYstatement.ThePARAMETERattributecan,
butneednot,bedeclaredforaparameter;itisinvalidto
usethatattributeforanyotherkindofvariable.Aparameter
describesagenerationofstoragepassedasanargumenttothe
procedurethatdeclarestheparameter.Thus,allocationand
freeingoftheparameteristheresponsibilityoftheprocedure's
caller.Sinceaparameterisallocatedbeforetheprocedure
declaringitisentered,theprocedureitselfcannotspecify
aninitialvaluefortheparameter.See"Argumentsand
Parameters"belowforfurtherinformationaboutparameters.

81

DefinedStorage
Thedefinedstoragetype,liketheparameterstorage
type,isanalias.Thedeclarationofadefinedvariable
specifiesabaseitem,whichisaportion(orpossiblyall)
ofsomeothervariable.Thedefinedvariableprovidesanother
wayofreferencingpartorallofthestorageoccupiedbythe
baseitem.Thebaseitemcanbepartofavariablehavingany
storagetypeotherthandefinedorbased,andsocircular
definingisexcluded.
Therearethreekindsofdefining:simpledefining,
isubdefining,andoverlaydefining.Thesortofdefiningthat
isineffectisdeterminedbytherelationbetweenthedefined
variableandthebasevariable.Sincedefinedvariablesare
aliases,theyarenotallocatednorfreed,norareinitial
valuesspecifiedforthem.
Anexampleofsimpledefiningis
DECLAREA(5,8)FIXED;
DECLAREADEF(2:4)DEFINED(A(1,*));
ADEFisdefinedtoconsistoftheelementsA(l,2),A(l,3),and
A(l,4).Forsimpledefiningtobeineffect,theattributes
ofthedefinedvariablemustagreewiththoseofthebaseitem,
exceptthatthearrayboundsofthedefinedvariablemaybemore
restrictivethanthecorrespondingboundsofthebaseitem.A
majoruseofsimpledefiningistospecifyportionsofarrays
thataretobepassedasargumentstoprocedures.

82

Isubdefiningisineffectwhenthebaseitemcontains
specialsubscripts,knownasisubs.Thesesubscriptshave
theform1SUB,2SUB,etc.Anexampleofisubdefiningis
DECLAREA(10,10)FIXED;
DECLAREADEF(9,8)DEFINED(A(lSUB+1,2SUB+2));
AreferencetoanelementofADEFistranslatedintoarefer
encetoanelementofAbysubstitutingthefirstsubscript
for1SUBandthesecondsubscriptfor2SUB.Forinstance,
ADEF(8,6)referstoA(9,8).Thedefinedarrayneednothave
thesamedimensionalityasthebaseitem.Forexample,in
DECLAREB(30,30)FLOAT;
DECLAREBDIAG(30)DEFINED(B(1SUB,1SUB));
theonedimensionalarrayBDIAGconsistsofthediagonal
elementsofthearrayB,whilein
DECLAREC(15)POINTER;
DECLAREC2(5,3)DEFINED(C(3*(lSUB1)+2SUB));
thetwodimensionalarrayC2isdefinedontotheonedimensional
arrayC.
Overlaydefiningisusedinordertoapplydifferent
descriptionstostrings.Forthepurposesofoverlaydefining,
characterdataandpicturesaretogetherconsideredas
characterclassdata,whilebitstringsareconsideredas
bitclassdata.Anexampleofoverlaydefiningis:

83

DECLARECSCHARACTER(30);
DECLAREODEF1(3)CHARACTER(5)POSITION(10)DEFINED(CS);
DECLARE
1ODEF2DEFINED(CS),
2OCSlCHARACTER(14),
2OCS2PICTURE'$$$V.$$';/*6CHARACTERPOSITIONS*/
TherelationshipbetweenCSandODEFl,andbetweenCSandODEF2,
isillustratedinFigure3.ThePOSITIONattributeinthe
declarationofODEFlindicatesthatthecharactersequence
comprisingODEFlstartsatcharacter10ofCS.ODEF(l)
consistsofcharacters1014ofCS,ODEFl(2)ofcharacters
1519ofCS,andODEFl(3)ofcharacters2024ofCS.The
treatmentofODEF2issimilar.Inoverlaydefiningboththe
definedvariableandthebaseitemmustconsistentirelyof
unaligneddata(see"Alignment"below)ofthesameclass,but
astringcanbeoverlaidontoanarrayaswellastheother
wayround.
Alignment
Thedeclarationofavariablecanspecifyanalignment,
eitherALIGNEDorUNALIGNED.Analignedvariableisstoredso
astofavorspeedofaccessoverspace;typically,storagefor
analignedvariableisplacedatawordboundaryorother
naturaldemarcationforthemachineathand.Anunaligned
variableisstoredsoastofavorspaceoverspeedofaccess,
andisarrangedinstoragesoastominimizeunusedspace.
Thedefaultalignmentfornonvaryingstringsandforpictures
isunaligned;foreverythingelseitisaligned.

84

(a)OverlayingODEFlontoCS

(b)OverlayingODEF2ontoCS

Figure3.ExampleofOverlayDefining

85

Inmostsituations,thealignmentofavariablehasno
effectonitsbehavior.Theexceptionisthataggregates
composedofunalignedstringsandpicturesarestoredwith
alltheircomponentsadjacent,i.e.,asasequenceofadjacent
characters(orbits,inthecaseofunalignedbitstrings).
Thesequencecanthenbeusedasabaseitemforoverlay
defining.
Initialization
Itispossibletospecifyaninitializationforavari
able,aslongasitsstoragetypeisnotanalias,i.e.,is
neitherparameternordefined.Theinitializationisspecified
usingtheINITIALattribute.Forexample,inthedeclaration
DECLAREA(40)FIXEDINITIAL((40)0);
thearrayAisinitializedtoallzeroes.Theinitialization
canbespecifiedbyasingleitem,byarepeateditem,orby
arepeatedlist,whichcanitselfcontainitemsofthesetypes.
Nestingtoanydepthispermitted.Thus
DECLAREB(20)FIXEDINITIAL(2,3,(5)4,(3)(1,2));
causesthefirst13elementsofBtobeinitializedtothe
sequence
2344444121212
Foramultidimensionalarray,initializationsareperformed
withthelastsubscriptvaryingmostrapidly.Thus
DECLAREC(3,2)FIXEDINITIAL(1,2,3,4,5,6);

86

causestheinitializations
C(l,l)=1
C(2,l)=3
C(3,l)=5

C(l,2)=2
C(2,2)=4
C(3,2)=6

Initializationalwaystakesplaceatthetimeofalloca
tion.Thus,forstaticvariables,theinitializationis
performedatthestartofprogramexecution.Forautomatic
variables,itisperformedateachentrancetothedeclaring
block.Forcontrolledandbasedvariables,itisperformed
whenanALLOCATEstatementforthevariableisexecuted,and
isappliedtothenewlyallocatedgeneration.Parameters
anddefinedvariablescannotbeinitializedwiththe
INITIALattribute

87

PROCEDURES,SCOPES,ANDENVIRONMENTS
Textually,aprocedureisabodyofcode,delimitedby
aPROCEDUREstatementatthebeginningandanENDstatement
attheend.Associatedwiththeprocedureareoneormore
entrypoints,eachofwhichprovidesawayofinvokingsome
portionofthecodecontainedwithintheprocedure.Theentry
pointsaredefinedbythePROCEDUREstatement,aswellasby
anyENTRYstatementsthatappearwithintheprocedure.The
characteristicsofanentrypointincludeitsname,the
numberandtypesofitsparameters,andthetypeofits
returnedvalue,ifany.Eachentrypoint,inturn,defines
anentryconstant.
Aprocedureiscalledeitherbymeansofafunction
referencewithinanexpressionorbymeansofasubroutine
referencewithinaCALLstatement.Theprocedurecallitself
consistsofanentryvaluedreferenceandanargumentlist,
possiblyempty.Forinstance,theprocedurecall
F(X+3,'INVALID')hasanentryvaluedreferenceFandan
argumentlistconsistingofthetwoargumentsX+3and
'INVALID'.ThevalueofFmustbeanentrypointofthe
procedurebeingcalled.UsuallyFisjustthenameofthe
procedure,butFcouldalsobe,forinstance,anentryvari
able.Anemptyargumentlistforafunctionreferencemustbe
indicatedexplicitlyby().Ifanentrypointreturnsa
value,thenitmustbecalledbyafunctionreference;other
wiseitmustbecalledbyasubroutinereference.

88

Anexampleofaproceduredefinitionis:
P1:
P2: PROCEDURE(QVAL,SIZE)RETURNS(FLOATBINARY);
DECLAREQVALFLOATBINARY;
DECLARESIZEFIXEDDECIMAL(4);
DECLAREJFIXEDBINARY;
DECLARETOTALFLOATBINARYINITIAL(0);
DOJ=1TOSIZE;
TOTAL=TOTAL+F(QVAL,J);
END;
RETURN(TOTAL);
P3: ENTRY(RVAL,RES,SIZE);
DECLARERVALFLOATBINARY;
DOJ=1TOSIZE;
RES=RES+F(RVAL,J);
END;
RETURN;
ENDP1;
Thisprocedurehasthreeentrypoints.P1andP2aresynonymous
(butdonotcompareequal),andareentryconstantsdesignating
theentrypointatthePROCEDUREstatement.Sincethatentry
pointreturnsavalue(withattributesFLOATBINARY),P1and
P2canonlybecalledasfunctionreferences,i.e.,ascompon
entsofanexpression.P3istheentryconstantnamingthe
entrypointstartingattheENTRYstatement.Itdoesnotreturn
avalue,andsoP3canonlybeinvokedfromaCALLstatement,
e.g.,by
CALLP3(A(2),B(2),22);
P2hastwoparameters,namely,QVALandSIZE,whileP3hasthree
parameters,namely,RVAL,RES,andSIZE.Asthisexampleshows,
theentrypointsneednothavethesameparameters,andifany
parametersareincommon,theyneednotappearinthesame
position.Itisinvalidtoreferenceaparameternotassociated

89

withtheentrypointactuallyusedtoenteraprocedure.For
instance,itisinvalidtoreferenceRVALiftheprocedureis
enteredthroughP1orP2.
TheRETURNStatement
TheRETURNstatementisusedtoendexecutionofaproce
dure.Itmayhaveeithertheform
RETURN(expr);
ortheform
RETURN;
Iftheprocedureiscalledbyafunctionreference,thenthe
RETURNstatementmustcontainanexpression.Conversely,if
theprocedureiscalledbyasubroutinereference,thenthe
RETURNstatementmustnotcontainanexpression.
WhenaRETURNstatementcontaininganexpressionis
executed,theexpressionisevaluated.Thevalueofthe
expressionisthentakenasthevalueofthefunctionreference
thatcalledtheprocedure.Ifnecessary,thevalueofthe
expressionisconvertedtothetypespecifiedintheRETURNS
clauseoftheentrypointwheretheprocedurewasentered.
Aprocedurecanreturnanaggregateaswellasascalar.
Moreover,thereturnedtypemayhaveasterisksinitsspeci
fication,e.g.,
RETURNS(CHARACTER(*));
foranentrypointthatreturnsacharacterstringofarbitrary
length.

90

ExecutionofaRETURNstatementnotcontaininganexpres
sionendsexecutionoftheprocedureandcausescontrolto
returntothepointofcall.TheENDstatementofaprocedure
istreatedashavinganimplicitRETURNstatementjustinfront
ofit,sothatifcontrolflowstotheENDstatement,execution
oftheprocedureisterminated.Itisanerrortoallowcontrol
toflowtotheENDstatementofaprocedurethatwascalled
asafunctionreference.

ArgumentsandParameters
Anentrypointofaprocedurecanhaveasequenceof
parametersassociatedwithit.Acallontheentrypointmust
includeacorrespondingsequenceofarguments,whichactas
inputstotheprocedure.If
(1)

theargumentisareferencetoavariable(possibly
subscriptedornamequalified),and

(2)

theattributesoftheargumentagreewiththose
oftheparameter,

thentheparameterbecomesanaliasfortheargument,and
assignmentstotheparameteraffecttheargument.Inall
othercases,theargumentisconsideredtobeadummy.That
is,whenthecallismade,agenerationofstoragethe
dummyissetasidefortheargument,andthevalueofthe
argumentiscopiedintothatgeneration.Ifthetypeofthe
argumentdisagreeswiththetypeoftheparameter,theargu
mentisconvertedtotheparametertypeandtheconvertedvalue
isassignedtothedummy.Theparameteristhenanaliasfor

91

thedummy,andafterthecalliscompletedthedummyis
discarded.Thus,assignmentstoaparameterthatcorresponds
toadummyargumenthavenoeffectatthepointofcall.
Constantsandexpressionsarealwayspassedasdummyarguments.
PL/Iusesthecallbyreferencemodelofargument
transmission,i.e.,thelocationoftheargumentispassedto
theprocedure.Theconventionsforargumenttransmissionare
shownbythefollowingexample:
CALLER:

PROCEDURE
DECLAREXFIXEDDECIMAL(5);
DECLAREYFLOATDECIMAL(7);
CALLCALLEE(X);/*XISSETTO12BYTHECALL*/
CALLCALLEE(Y);/*DUMMYCREATED,SOYISUNCHANGED
CALLCALLEE(24962);/*DUMMYCREATED*/
CALLCALLEE((X);/*DUMMYCREATEDSINCE(X)IS
ANEXPRESSSION*/
CALLCALLEE(X+14);/*DUMMYCREATEDHERE,TOO*/
ENDCALLER;

CALLEE:

PROCEDURE(P);
DECLAREPFIXEDDECIMAL(5);/*PISTHEPARAMETER*/
P=12;
ENDCALLEE;

Arraysizes,stringlengths,andareasizesofparameters
mustbegiveneitherbyconstantvaluedexpressionsorby
asterisks.Anasterisksizeisusedwhenthesizeofthe

92

correspondingargumentisunknown,orvariesfromonecallto
another.ThusaparameterdeclaredasCHARACTER(*)willmatch
anargumentdeclaredasCHARACTER(e),whereeisanyexpression
However,suchaparameterwillnotmatchanargumentdeclared
asCHARACTER(e)VARYING.
Options
Implementationdefinedinformationcanbeattachedeither
toaPROCEDUREstatementortothedeclarationofanentry
constantbymeansoftheOPTIONSattribute.Aparticularly
commonoption(butnotauniversalone)isillustratedby
PROCEDUREOPTIONS(MAIN);
wheretheMAINoptionindicatesthatexecutionoftheprogram
istostartwiththisprocedure.Ingeneral,theinformation
giveninanOPTIONSattributeaffectsthemannerinwhichthe
procedureiscompiled.
WhenaPL/Iprocedurereferencesaprocedurewrittenina
differentprogramminglanguage,theOPTIONSattributecanbe
usedtospecifythelanguageofthatforeignproceduresothat
appropriatecallingsequencescanbecompiled.Forinstance,
DECLAREPRIMFNENTRY(FLOAT)RETURNS(FLOAT)
OPTIONS(FORTRAN);
woulddescribeaprocedurewritteninFortrantobecalledfrom
aprocedurewritteninPL/I.

93

Recursion
APL/Iprocedureispermittedtocallitself,either
directlyorindirectly.Aprocedurethatcallsitselfis
saidtoberecursive,andtheRECURSIVEoptionmustbe
specifiedonthePROCEDUREstatementofsuchaprocedure.
Anexampleofarecursiveprocedureisonethatcountsthe
numberofnodesinabinarytree.Eachnodeisrepresented
asabasedstructure,andcontainsavalue,aleftson,and
arightson.Eachsoniseitheritselfapointertoabinary
tree,ornull.TheprocedureinPL/Iis:
COUNTNODES:
PROCEDURE(NODEPTR)RECURSIVERETURNS(FIXED);
DECLARE(LCOUNT,RCOUNT)FIXEDINITIAL(0);
DECLARE
1NODEBASED(NODEPTR),
2LEFT_SONPOINTER,
2RIGHT_SONPOINTER,
2VALUEFIXED;
DECLARENODEPTRPOINTER;
DECLARENULLBUILTIN;
IFLEFT_SON=NULLTHEN
LCOUNT=COUNTNODES(LEFT_SON);
IFRIGHT_SON=NULLTHEN
RCOUNT=COUNTNODES(RIGHT_SON);
RETURN(LCOUNT+RCOUNT+1);
ENDCOUNTNODES;
Theprocedureisgivenapointertoabinarytreeasan
argument,anditreturnsthenumberofnodesinthetreeas
itsvalue.Recursivenessisapropertyofaprocedurerather
thanofitsentrypoints,sothateveniftherecursivecall
isonadifferententrypoint,theprocedureisstill
consideredtoberecursive.

94

TheGENERICAttribute
Oftenitisusefultocreateafamilyofentrypointsthat
performasimilarfunctionbutthatexpectsomewhatdifferent
arguments,andtoassignasinglenametothefamily.The
GENERICattributeallowsasinglename,knownasageneric
function,tobeusedforsuchafamilyofentrypoints;the
choiceofentrypointsthendependsonthenatureoftheargu
ments.TheGENERICattributespecifiesalistofentrypoint
names,andassociatesasequenceofgeneralizeddescriptors
witheachname.Areferencetothegenericfunctionis
translatedintoareferencetothefirstentrypointwhose
descriptors,asgivenbytheGENERICattribute,matchthe
argumentsofthegenericfunction.Anasteriskindicatesa
descriptorthatmatchesanything.Thetestfordescriptor
matchingissatisfiedifthedescriptorintheGENERICattribute
iscontainedintheattributesetoftheargument;theattribute
setcancontainattributesnotinthedescriptor.Onlydata
attributescanbetestedinthisway.
AnexampleofaGENERICattributeis
DECLAREGFGENERIC(GlWHEN(FIXED,FIXED),
G2WHEN(FIXED,*),
G3WHEN(*));
Usingthisdeclaration,andassumingthefurtherdeclarations
DECLAREXFIXEDBINARY;
DECLAREYFLOATDECIMAL;
thereference

95

GF(X,X+1)

translatestoG1(X,X+1)

GF(X,Y+1)

translatestoG2(X,Y+1)

Thereference

sincetheexpressionY+1hasdatatypefloat.Thereference
GF(X)

translatestoG3(X)

sincethefirsttwodescriptorsequenceseachrequiretwo
arguments.
AnotherapplicationoftheGENERICattributeis
illustratedbythedeclaration
DECLAREVARFNGENERIC(NFlWHEN(FLOAT(1:20)BINARY),
NF2WHEN(FLOAT(21:40)BINARY),
NFSWHEN(*));
Inthiscase,theentrypointrepresentedbyVARFNisselected
onthebasisoftheprecisionoftheargument,whichisassumed
tobefloatbinary.Iftheargumenthasfrom1to20binary
digits,NFlisused;iftheargumenthasfrom21to40binary
digits,NF2isused;andiftheargumenthasmorethan40
binarydigits,NF3isused.
BlocksandScopes
Ablockconsistsofasequenceofstatements,starting
withaPROCEDUREstatementoraBEGINstatementandextending
tothematchingENDstatement.Blocksofeitherkindcanbe
nested.Theprimaryeffectoftheblockstructureofaprogram
istodefinethescopeofaname,i.e.,thesetofstatements
fromwhichthenamecanbereferenced.Anamedeclaredina

96

DECLAREstatementbelongstotheinnermostblockcontaining
thatDECLAREstatement.However,anamecanalsobedeclared
byvirtueofitsappearanceasaparameterorasastatement
name.AstatementnamethatnamesaPROCEDUREstatement,an
ENTRYstatement,oraBEGINstatementbelongstotheblock
outsidetheonethatcontainsthatstatement;anyother
statementnamebelongstotheblockcontainingthestatement
thatitnames.Thisruleisneededinordertoallow
procedurestobecalledfromtheoutside.Areferencetoa
nameisresolvedbysearchingthenestofblocksforadeclar
ationofthename,workingfromtheinsideout,andstarting
withthestatementcontainingthereference.Anotherway
oflookingatitisthatthescopeofanameconsistsofthe
blockdeclaringthenameandallcontainedblocksexcept
forthoseinwhichthescopeisoccludedbyaninnerdeclara
tionofthesamename.
Anexampleillustratingthescopeofnamesisgivenin
Figure4.Theparenthesizednumbersareusedtodistinguish
differentdeclarationsofthesameidentifier.Thereisan
imaginaryouterblockusedtoholdthedeclarationsofthe
entrypointsoftheexternalprocedure(AandBinthiscase),
Thisblockisneededsincetheentrypointsofaprocedure
belong,nottotheblockoftheprocedureitself,buttothe
nextouterblock.Sincethereisnosuchblockforthe
externalprocedure,onemustbecreated.

97

Figure4.ExampleIllustratingScope
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

A:

B:
C:

D:

E:
F:
G:

PROCEDURE;
DECLAREXCHARACTER(1);
DECLAREBFIXED;
statementsequence1
ENTRY(Y);
statementsequence2
BEGIN;
DECLAREWFIXED;
DECLAREYPICTURE'(6)$';
statementsequence3
PROCEDURE;
DECLAREWFLOATCOMPLEX;
statementsequence4
ENDD;
ENDC;
PROCEDURE;
DECLAREWFLOAT;
Statementsequence5
B=3;
ENTRY;
statementsequence6
ENDE;
ENDA;

Statementsbelongingto
differentblocks:

Namesbelongingto
differentblocks:

outer
A(1)

none
1,2,3,4,5,6,23

outer
A(1)

C(7)

7,8,9,10,15

C(7)

A(l),B(5)
X(2),B(3),Y(5),C(7),
E(16),G(20)
W(8),Y(9),D(11)

D(ll)

11,12,13,14

D(ll)

W(12)

E(16)

16,17,18,19,20,21,22

E(16)

W(17),F(19)

Y(9)
D(11)
W(12)
E(16)
W(17)
F(19)
G(20)

715
715
1114
123
1622
1622
123

Statementsinscopesofthesenames:
A(1)
X(2)
B(3)
B(5)
Y(5)
C(7)
W(8)

123
123
123
none
16,1623
123
710,15

98

InternalandExternalScope
Inmostcases,declarationsaredefaultedtohaveinternal
scope,meaningthatthedeclarationdesignatesanobject
distinctfromtheobjectsdesignatedbyotherdeclarations
ofthesameidentifier.Forinstance,ifthevariableQis
declaredinthreedifferentblocksofaprocedurewiththe
INTERNALattribute(possiblybydefault),theneachofthese
blockshasitsowndistinctQ.However,severaldeclarations
canbemadetorefertothesameobjectbygivingthemexternal
scope.Externalscopecannotbeappliedtojustanydeclara
tion;itisrestrictedtothestaticandcontrolledstorage
classes,andtonamedconstants.Identifiersdeclaredtobe
externalmustnecessarilyhavethesameattributes.Asan
example,ifthedeclaration
DECLAREA(14)STATICEXTERNAL;
appearsintwodifferentblocks,thenbothdeclarationsrefer
toasinglearray.IfanassignmentismadetoA(4)while
executingoneoftheseblocks,thenthechangewillbevisible
intheother.Declarationsofanexternalidentifiercan
appearbothwithinasingleexternalprocedureandamongseveral
externalprocedures.Thedefaultscopeformanifestlydeclared
entryconstantsisexternal,sinceexternalprocedureshave
tobedeclaredbytheprogrammerwhileinternalproceduresare
automaticallydeclared.

99

EntryValuesandEnvironments
OnaccountoftherulesforscopeofnamesinPL/I,a
procedurecanrefertonamesinblockssurroundingtheproce
dure.Moreover,anentrypointdefinesanentryvalue,and
thatvaluecanbeassignedtoanentryvariableandsubsequent
lyinvoked.Invocationoftheentrypoint,inturn,requires
thatreferencestoouterblocknamesberesolvedproperly.
Inordertoachievethiseffect,anentryvaluecontainsnot
onlyadesignationofanentrypointbutalsoanenvironment.
Whentheblocksurroundingtheentrypointisentered,the
environmentoftheentrypointisdefined.Theentryvalue
correspondingtotheentrypointthenconsistsoftheentry
pointitselftogetherwitharecordofallnamesinherited
fromouterblocksandthevariables(orconstants)thatthese
namesdenote.Inthecaseofrecursiveprocedures,the
environmentimplicitlydesignatesnotonlyasetofvariables,
butalsoarecursionlevel.Thefollowingexampleillustrates
theseconcepts:
P:
Q:

S:

T:

PROCEDURE;
PROCEDURE(R,LEVEL)RECURSIVE;
DECLARERENTRY;
DECLARELEVELFIXED;
IFLEVEL=10THEN
CALLR();
ELSEIFLEVEL=6THEN
CALLQ(S,7);
ELSE
CALLQ(R,LEVEL+1);
PROCEDURE;
PUTDATA(LEVEL);
STOP;
ENDS;
ENDQ;
PROCEDURE;
ENDT;
CALLQ(T,1);
ENDP;
100

ThecallonQonthenexttothelastlineinitiatesanest
ofrecursivecalls.Oneachcall,thevalueofLEVELincreases
by1.Atthetoplevel,theentryvalueTispassedasan
argumenttoQ;butsincethisentryvalueisneverinvoked,
itservesonlyasaplaceholder.Atthesixthlevelof
recursion,theentryvalueSispassedaspartoftherecur
sivecallonQ.Theenvironmentofthisentryvalueconsists
ofthecurrentsetofouterblockvariablesouter,thatis,
toS.Inparticular,sinceSisinternaltoQ,thecurrent
valueofLEVEL6inthis.caseispartoftheenvironment
accompanyingtheentryconstantS.Onsubsequentrecursive
calls,theentryvalueissimplypassedalong(cf.thecall
withparametersRandLEVEL+1).Whentherecursionlevel
reaches10,Riscalled.ThevalueofRistheentryconstant
Sobtainedatlevel6,andso
LEVEL=6
isprintedoutandtheprogramhalts.
ThePL/Irulesforblockstructure,scopingofnames,and
environmentsarederivedfromAlgol60.Infact,itispossible
totranscribetheexampleaboveratherdirectlyintoAlgol60,
andthebehaviorinAlgol60wouldbethesame.

101

ONUNITSANDONSTATEMENTS
OneofthemoreinnovativeaspectsofPL/Iisthefacility
thatitprovidesforhandlingexceptionalconditionsthe
socalledONconditions.Anexceptionalconditionmayarise
eitherastheresultofanerror,suchasasubscriptoutof
range,orfromananticipatedevent,suchasencountering
endoffilewhilereadingfromadatasetorreachingtheend
oftheprogram.PL/IhasasetofONconditionscorresponding
totheseexceptionalconditions.Whentheconditionoccurs,
itissaidtoberaised.UsinganONstatement,theprogrammer
canspecifyaresponsetotheconditionintheformofa
statement(orbeginblock)tobeexecuted.Thatresponseis
knownastheONunit.IfnoONunithasbeenspecified,a
standardONunit,knownasthestandardsystemaction,is
executed.DependingonthenatureoftheONcondition,itmay
bepossiblefortheprogramtocontinuewhereitleftoffafter
theONunitisexecuted.ThedifferentkindsofONconditions
arelistedinTable7.
AnexampleillustratingtheuseofONconditionsand
ONunitsis:
P:

PROCESS:

PROCEDURE;
...
ONENDFILE(SYSIN)
GOTOPROCESS;
DOWHILE('1'B);
READFILE(SYSIN)INTO(LINE_IMAGE);
...
END;
...
ENDP;

102

103

104

Inthiscase,theONENDFILEstatementspecifiesthatwhen
endoffileisencounteredonthefileSYSIN,thestatement
GOTOPROCESS;istobeexecuted.Thusthefilewillberead
uptoitsend,andafterwardsthestatementsatPROCESSwill
beexecuted.
TheONStatement,REVERTStatement,andSIGNALStatement
TheONstatementspecifiesalistofONconditions
togetherwithanONunit.TheassociationoftheONunitwith
theONconditionsisnotmadeuntiltheONstatementis
actuallyexecuted.Moreover,executionofasubsequentON
statementcansupersedetheeffectofanearlierone.For
instance,afterexecutionofthetwoONstatements
ONOVERFLOW,FIXEDOVERFLOW
GOTOTOOBIG;
...
ONFIXEDOVERFLOW
GOTOFIXEDBIG;
theONunitassociatedwiththeOVERFLOWconditionis
GOTOTOOBIG;
whiletheONunitassociatedwiththeFIXEDOVERFLOWconditionis
GOTOFIXEDBIG;
ONstatementshaveblockscope,inthesensethattheyare
effectiveonlyuntiltheblockcontainingthemisterminated.
Whenexecutionofablockiscompleted,theassociationbetween
ONconditionsandONunitsrevertstowhatitwasintheprevi
ouslyexecutingblock.

Thusaprocedurecanactivatecollection

105

ofONunitsappropriatetoitscircumstanceswithoutaffecting
theONunitssetupbyitscaller.
TheONunititselfcanbeeitheraBEGINblock(delimited
byBEGINandEND)orasingleunconditionalstatement.In
particular,anONunitcannotbeeitheraDOgrouporanIF
statement.ActualexecutionoftheONunitiscarriedoutas
thoughtheONunitwereaprocedure.Inparticular,ONunits
carryenvironmentswiththem,andsoanynamesoccurringinan
ONunithavethemeaningapplicableatthepointofexecution
ofthecorrespondingONstatement.
AnONstatementcanspecifythestandardsystemactionas
anONunit,usingthekeywordSYSTEM.Thus
ONSUBSCRIPTRANGE
SYSTEM;
specifiesthatthestandardsystemactionistobetakenifthe
SUBSCRIPTRANGEconditionisraised.Thisfacilitycanbeused
tonullifytheeffectofpreviouslyexecutedONstatements.It
isalsopossibletospecifythatatraceback,orotherdebugging
information,istobeprintedintheeventthataconditionis
raised.ThateffectisgottenbyusingtheSNAPkeyword,asin
ONSIZESNAPSYSTEM;
IftheSIZEconditionisraised,thestandardsystemactionwill
betaken,butinadditiondebugginginformationwillbeprinted.
Theactualchoiceofdebugginginformationisimplementation
defined.Thestatement
ONSIZESNAP;

106

wouldproduceadifferenteffect:iftheSIZEconditionis
raised,thenullstatement,whichdoesnothing,willbeexecuted,
Infact,thenullstatementisnotavalidONunitforthe
SIZEconditionbecauseitdoesnotterminateinaGOTO
statement.ThequestionofvalidityofsuchONunitsis
discussedbelow.
TheREVERTstatementcanbeusedtocanceltheeffectof
anONstatement,orseveralofthem,withoutknowingwhatON
conditionwasineffectpreviously.TheREVERTstatementspeci
fiesalistofONconditions.ExecutionoftheREVERTstatement
causestheONunitforeachoftheseconditionstorevertto
whatitwasinthepreviouslyexecutingblock.Thus,inthe
sequence:
ONENDFILE(SYSIN)
CALLENDER;
BEGIN;
...
ONENDFILE(SYSIN)
GOTOALT_END;
...
REVERTENDFILE(SYSIN);
END;
theREVERTstatementcausestheoncondition
CALLENDER;
toagainbeassociatedwiththeENDFILEconditionforthefile
SYSIN.
TheSIGNALstatementisusedtoraiseaspecifiedON
condition.Forexample,thestatement
SIGNALZERODIVIDE;

107

causestheZERODIVIDEconditiontoberaisedandtheappropri
ateONunit(possiblythestandardsystemaction)tobeinvoked.
Thisstatementisparticularlyusefulindebuggingprogramlogic
forhandlingONconditions.Itisalsotheonlywaytoraise
aprogrammerdefinedcondition(discussedbelow).
EnablementandDisablement
AnumberoftheONconditionsrequiretimeconsumingcode
(onmostmachines,atleast)inordertocheckwhetherornot
theyhaveoccurred.Thetimeneededtocheckwhetherasub
scriptisoutofrange,forinstance,wellmaydominatethe
timeneededfortheretrievalofasubscriptedvariable.There
forePL/Iallowstheprogrammertoeitherenable(turnon)or
disable(turnoff)thecheck.Enablementanddisablementare
providedonlyforcertainONconditions.Theyarespecifiedby
meansofaconditionprefix,whichconsistsofeitheranON
conditionnameorthenegationofanONconditionname,inparenthesesand
followedbyacolon.Theconditionprefixcan
beappliedeithertoasinglestatementortoablock.For
example,inthesequence:
P:
(NOOVERFLOW):

(OVERFLOW,NOSIZE):
PROCEDURE;
...
Q=A+BTR(I);
...
END;

theSIZEconditionisdisabledthroughouttheprocedureP,while
theOVERFLOWconditionisenabledthroughoutPexceptforthe

108

singlestatementwhereNOOVERFLOWisindicated.Forthat
statement,theconditionisdisabled,andnotestwillbemade
forit.Ifaconditionisraisedinastatementwhereit
hasbeendisabled,thatisconsideredtobeaprogrammererror,
andtheimplementationisnottobeheldresponsibleforits
consequences.
Enablementanddisablementarestaticpropertiesofa
program.Inotherwords,itispossibletotellwhethera
particularONconditioniseitherenabledordisabledfora
particularstatementjustbylookingattheprogram,without
consideringwhatitssequenceofexecutionis.Inthisrespect,
enablementanddisablementdifferfromtheONstatements,
whoseexecutiondependsonprogramflow.Enablementanddis
ablementaffectwhetheraconditionisorisnottobetested
for,whileONstatementsdeterminewhatactionistobetaken
iftheconditionisraised.Thestatement
ONUNDERFLOW;
doesnotdisabletheUNDERFLOWcondition;itmerelystatesthat
ifthatconditionisdetected,thenullstatementistobe
executed.
BuiltinFunctionsforONConditions
DuringtheexecutionofanONunit,anumberofbuiltin
functionsareavailableinordertodeterminethecircumstances
thatcausedthecorrespondingONconditiontoberaised.Some
oftheseapplytoallONconditionsandarediscussedhere;

109

otherarespecifictoparticularONconditionsandare
discussedinconnectionwiththoseconditions.Ingeneral,
thesebuiltinfunctionsdonothavemeaningfulvaluesexcept
inthecontextofanONunit.Theyareallfunctionsofno
arguments.
TheONCODEbuiltinfunctionhasasitsvalueanimple
mentationdefinedintegerusedtoindicatewhytheactiveON
conditionwasraised.Aparticularconditionmayhavemore
thanonecodevalueassociatedwithit.Onecommonconvention
isthatthevalueofONCODEiszeroiftheONconditionwas
raisedbyaSIGNALstatement.TheONLOCbuiltinfunction
returnsasitsvaluethenameoftheinnermostentrypoint
activewhentheconditionwasraised.Forinputoutputrelated
ONconditions,theONFILEbuiltinfunctionhasasitsvalue
thenameofthefilethatwasbeingoperateduponwhenthecon
ditionwasraised.ThevaluesofbothONLOCandONFILEare
intheformofcharacterstrings.
CategorizationoftheONConditions
ThevariousONconditionslistedinTable7canbebroken
downintothreegroups.Thefirstgroupconsistsofthecompu
tationalONconditions.Mostconditionsinthisgroupare
raisedinresponsetoaparticularkindoferror.Thecomputa
tionalONconditionsaretheonlyonesthatcanbeenabled
anddisabled.Theyare:

110

CONVERSION
FIXEDOVERFLOW
OVERFLOW
SIZE
STRINGRANGE
STRINGSIZE
SUBSCRIPTRANGE
UNDERFLOW
ZERODIVIDE
Theoccurrenceofoneoftheseconditionsusuallymeansthata
badresulthasbeengenerated,andsotheactivecomputation
cannotbecontinued.Forthisreason,theONunitsassociated
withmostoftheseconditionsmustnotterminatenormally,
i.e.,mustcauseatransferofcontroloutoftheONunitby
meansofaGOTOstatementorsimilarconstruction.Normal
terminationwouldmeanthattheactivecomputationwouldbe
resumed,andthenatureoftheconditionissuchthatthe
computationcannotberesumed.Forinstance,ifasubscript
isoutofrangeonanarrayreference,thereisnowayto
obtainanappropriatevalueforthereference.
ThreeofthecomputationalONconditionsaretreated
somewhatdifferently.TheCONVERSIONconditionisraisedwhen
dataisbeingconvertedfromcharactertosomeothertype.
Whenthisconditionisraised,theprogrammercanmodifythe
characterstringtobeconverted.Ifanormalreturntakes
placefromtheONunit,i.e.,theONunitcompleteswithout
atransferofcontrol,theconversionisreattemptedwiththe
modifiedinputstring.
Twobuiltinfunctionsareavailableforthemodification:
ONSOURCEandONCHAR.ONSOURCEhasasitsvaluethecharacter
stringtobeconverted,whileONCHARhasasitsvaluetheleft

111

mostcharacterinthatstringforwhichnovalidcontinuation
exists.ByexaminingONSOURCEandONCHAR,theprogrammermay
beabletodeterminethedifficultyandwhattodoaboutit.
Moreover,ONSOURCEandONCHARcanbeusedontheleftsideof
anassignment(withinanONunitfortheCONVERSIONcondition),
andsothestringtobeconvertedcanbemodifiedbyassign
mentstoeitherONSOURCEorONCHAR(whichcanalsobeusedas
pseudovariables).Forexample,ifacharacterstringisbeing
convertedtoabitstringthefollowingONunitmightbe
appropriate:
ONCONVERSIONBEGIN;
DECLAREONCHARBUILTIN;
IFONCHAR=''THEN
ONCHAR='0';
ELSEONCHAR='1';
END;
Ifthestringtobeconverteddoesnotconsistentirelyofones
andzeros,eachblankinthatstringwillbereplacedbyazero,
andeachotherdeviantcharacterwillbereplacedbyaone.
TheUNDERFLOWconditionalsoreceivesslightlydifferent
treatment.NormalreturnfromtheUNDERFLOWconditionis
permitted,andthevalueofthecomputationthatunderflowedis
takentobezero.TheSTRINGSIZEconditionariseswhenastring
isshortenedasaresultofaconversionorassignment.Upon
normalreturnfromtheONunit,thestringistruncatedonthe
righttotherequiredlength.Sincethestandardsystemaction
inthiscaseistodonothing,thisconditionisoftenignored.
However,itcanbeusedineitheroftwoways.Ifitisdisabled,
thenthecompilerneednotproducecodetocheckforstring

112

overflow.Moreover,ifanonstandardONunitisprovided,
thentheprogrammercantakesomeaction.However,thereis
nowaythattheprogrammercanmodifytheresultproduced
eitherfortheUNDERFLOWconditionorfortheSTRINGSIZE
condition.
ThesecondgroupofONconditionsistheinputoutput
conditions.Eachoftheseconditionsisassociatedwitha
particularfile,specifiedalongwiththeconditionname.
Theinputoutputconditionsare:
ENDPAGE
ENDFILE
KEY
NAME
RECORD
TRANSMIT
UNDEFINEDFILE
Someoftheseconditionsarediscussedfurtherinconnection
withinputoutput.
Theremainingconditionsaremorevaried.Theseare:
AREA
CONDITION
ERROR
FINISH
STORAGE
TheAREAconditionisraisedwhenanallocationisattemptedin
anarea,andthereisinsufficientspacefortheallocation.
IftheassociatedONunitreturnsnormally,theareareference
intheALLOCATEstatementisreevaluated,andtheallocationis
reattempted.ThereforeanappropriateresponsetotheAREA
conditionistoassignanewareavaluetotheareavariable
referencedintheALLOCATEstatement.

113

TheprogrammercandefineONconditionsusingthekeyword
CONDITIONandanidentifier,knownastheconditionname.ON
unitscanbeprovidedforprogrammernamedconditions,butthey
canonlyberaisedbyaSIGNALstatement.Forinstance,a
programmermightwrite:
ONCONDITION(TABLE_OVERFLOW)
CALLOVERFLOW_RECOVERY;
andthen,insomeotherpartoftheprogram,write:
IFT>TABSIZETHEN
SIGNALTABLE_OVERFLOW;
TheERRORconditionisraisedunderavarietyofcircum
stances,someofwhichcanbeimplementationdefined.

The

standardsystemactioninresponsetoanumberofotherON
conditionsistocomment(i.e.,displaydiagnosticinformation)
andthentoraisetheERRORcondition.(Itisquiteacceptable
tohaveanONunitraiseanONconditionitself.)
TheFINISHconditionisraisedwhentheprogramcompletes.
Itdiffersfromallotherconditionsinthatitisraisedas
anormalaspectofprogramexecution.TheSTORAGEconditionis
raisedwhentheprogramrunsoutofstorage.Sinceprograms
consumestorageinmanydifferentways,theexactcircumstances
underwhichitisraisedareimplementationdefined.Recovery
fromthisconditionmayormaynotbepossible.

114

OTHERSTATEMENTSAFFECTINGFLOWOFCONTROL

ConditionalStatements
Theconditionalstatementisusedinordertotesta
conditionandtakesomeactiondependingontheresult.A
conditionalstatementstartswithanIFstatement,specifying
thetest,andmayincludeanELSEpartthatspecifieswhat
actiontotakeifthetestfails.Forinstance,thesequence
IFQ<=QMAXTHEN
INDEX=INDEX+1;
ELSE
GOTOPART_7;
causestheassignment
INDEX=INDEX+1;
tobeexecutediftheconditionQ<=QMAXistrue,andthe
statement
GOTOPART_7
tobeexecutedotherwise.ThestatementfollowingeitherTHEN
orELSEcanitselfbeaconditionalstatement,sothatnests
ofconditionalstatementscanbebuiltup.Moreover,either
THENorELSEcanbefollowedbyaDOgroup(discussedbelow),
sothatseveralstatementscanbeexecutedafterthetest
ratherthanjustone.Anexampleofamorecomplicated
conditionalstatementis:

115

IFA(I)=0THENDO;
SIZE1=SIZE1+INCR;
SIZE2=SIZE2INCR;
IFSIZE2<SIZE1THEN
CALLADJUST;
END;
END;IFA(I)>0THEN
SIZE2=SIZE2+INCR;
ELSE
SIZE1=SIZE1INCR;
ItisnotnecessarythateachIFstatementhaveacorresponding
ELSEstatement.Incomplicatedconditionalstatements,each
ELSEispairedwiththenearestprecedingunpairedIF,working
fromfronttoback.
ThetestinanIFstatementactuallytakestheformof
anexpression,whichisevaluatedandconvertedtoabit
string.Sincethecomparisonoperatorsallproduceonebit
results,andsincethelogicaloperatorsalsoproduceonebit
resultswhentheiroperandsareonebitvalues,theconversion
isusuallyunnecessary.Ifthebitstringobtainedby
evaluatingthetestexpressionhasatleastoneonebitinit,
thetestsucceeds,andotherwiseitfails.Thetestexpression
mustbescalarvalued,althoughifitisnotscalarvaluedthe
SOMEandEVERYbuiltinfunctionscanbeusedtoreduceitto
ascalarvalue.
TheDOStatement
TheDOstatementhasthreemainvariants:thesimpleDO,
theDOWHILE,andthespecifiedDO.ThesimpleDOisusedin
ordertoconvert,syntactically,asequenceofstatementsinto
asinglestatement.AsimpleDOgrouphastheform:

116

DO;
statementsequence
END;
Thestatementsinthesequenceareexecutedjustonce.Transfers
ofcontrolintoandoutofthesequencearepermitted.Themain
useofthesimpleDOgroupisaspartofaconditionalstatement,
TheDOWHILEvarianthastheform:
DOWHILE(expression);
ADOWHILEgroupconsistsofaDOWHILEstatementfollowedby
astatementsequenceandamatchingENDstatement.Thestate
mentsinthegroupareexecutedrepeatedly,andtheexpression
intheDOWHILEstatementistestedbeforeeachexecution.If
thetestfails,controlistransferredtothestatementfollow
ingthegroup.Iftheexpressionisinitiallyfalse,thegroup
isnotexecutedatall.AnexampleofaDOWHILEgroupis:
DOWHILE(CVAL>0);
DVAL=DVAL+G(CVAL);
CVAL=CVALDVAL;
END;
ThespecifiedDOitselfhasanumberofvariants.Aswith
theothertwoforms,aDOgroupconsistsofaspecifiedDO
statementfollowedbyastatementsequencefollowedbyanEND
statement.Themostcommonvariantisillustratedby:
DOM=0TO100BY2;
Inthiscasethestatementsinthegroupareexecutedrepeatedly.
Beforethefirstexecution,Misassignedthevalue0.Mis
thenincreasedby2oneachexecutionofthegroup,andhas

117

thevalue100onthelastexecutionofthegroup.Uponcomple
tionoftheentiregroup,thevalueofMis102.However,
transferoutofthegroupispermitted,andifthathappens,
Mretainsthevalueassignedtoitonthemostrecentiteration.
TheTOclauseandtheBYclausecanbewrittenineither
order,andeitherofthemcanbeomitted.IftheTOclauseis
omitted,thegroupisiteratedindefinitely,i.e.,untila
transferofcontroloutofthegrouptakesplace.IftheBY
clauseisomitted,avalueof1isassumedforit.Oneach
iteration,thecontrolvariable(thevariablefollowingthe
keywordDO)isincrementedbythevaluegivenintheBYclause.
IftheBYclausehasanegativevalue,thenthecontrolvari
ableisdecrementedratherthanincremented.Theloopterminates
whenthevalueofthecontrolvariableisgreaterthanthe
valueoftheTOclause(forapositiveBYvalue)orlessthan
thevalueoftheTOclause(foranegativeBYvalue).Ifthe
terminationtestissatisfiedbytheinitialvalueofthe
controlvariable,thegroupisexecutedzerotimes.Ifneither
theTOclausenortheBYclauseappears,thegroupisexecuted
forasinglevalueofthecontrolvariable.
TheTOclauseandtheBYclausearebothevaluatedprior
toexecutionofthestatementswithintheDOgroup.Thusany
changestovaluesofvariablesthatappearwithintheTOclause
ortheBYclausehavenoeffectoncetheiterationhasstarted.
Thecontrolvariableneednothavearithmetictype;astringor
picturedtypeisalsoacceptable.AWHILEclausecanalsobe
specified,e.g.,

118

DOJV=XBYYWHILE(PROP(JV)<PROP(JV+1));
Anothervariantisillustratedby:
DOP=LIST_HEADREPEAT(P>NEXT)WHILE(P=NULL);
or
DOSTRING=''REPEAT(STRING||CHARS(I))WHILE(LENGTH(STRING)<LMAX);
Thecontrolvariableisassignedthegiveninitialvalueon
thefirstiteration.Onsubsequentiterations,thevalueof
theREPEATclauseisrecalculatedandassignedtothecontrol
variable.TheWHILEclausecanbeomitted,althoughusually
itisdesirabletoincludeit.
ThespecifiedDOcanconsistofasequenceofspecifications
ratherthanasingleone.Forinstance,thestatement
DOM=3,7,M+2BY3TO15,0;
executesthegroupofstatementsthatfollowsforthesequence
ofvalues3,7,9,12,15,0.Eachspecificationinthegroup
canhavethegeneralformsdescribedabove.
TheGOTOstatement
TheGOTOstatementcausescontroltobetransferredto
thelabelspecifiedinthestatement.Thestatementactually
specifiesalabelvaluedexpression,andalthoughthatexpres
sionnormallyisaconstant,i.e.,astatementname,itneed
notbe.Forinstance,itcouldbeasubscriptedreferenceto
anarrayofstatementnames,sothattheappropriatedestina
tionisselectedbythevalueofanindex.

119

ThedestinationofaGOTOstatementneednotbeinthe
sameblockasthestatementitself.Ifthedestinationis
inadifferentblock,thentheeffectofthestatementisto
terminateexecutionofthecurrentblockandallblocks
betweenthestatementanditsdestination.Inotherwords,
atthemomentwhentheGOTOstatementisexecuted,therewill
beahierarchyofactiveblocks,withthecurrentblocklast
inthehierarchy.ThelabelvalueobtainedfromtheGOTO
statementmustdesignate,asitsenvironmentcomponent,some
blockinthehierarchy.Thenallblocksbetweenthedesignated
blockandthecurrentblock,aswellasthecurrentblock
itself,areterminated.Thedesignatedblockthenbecomes
thecurrentblock,andcontrolistransferredtothestatement
namedbythelabelvalue.
AGOTOstatementwhosedestinationisnotinthesame
blockasthestatementitselfiscalledanonlocalgoto.
Anonlocalgotoisexpensivetoexecuterelativetoalocalone.
ThereforetheprogrammerisallowedtodeclaretheLOCAL
attributeforalabelvariable.TheLOCALattributeconsti
tutesaclaimbytheprogrammerthatanyGOTOstatementusing
thevalueofthatlabelvariablewillbealocalgoto.Thus
thecompilerneednotexaminetheenvironmentassociatedwith
thelabel,andcangenerateinstructionstoexecutethe
requestedtransferofcontroldirectly.

120

TheSTOPStatementandtheNullStatement
TheSTOPStatementhastheform
STOP;
andisusedtostopexecutionoftheprogram.Ithastheeffect
ofterminatingtheexecutionofallcurrentlyactiveblocks.
Thenullstatementhasnotextatall;itiswrittenas
justasemicolon.Itsmainusesaretoplaceastatementname,
tofilloutabranchofaconditionalstatementwherenoaction
istobetaken,andtospecifythatnoactionistobetakenin
responsetoaspecifiedONcondition.

121

FILESANDRECORDINPUTOUTPUT
FileAttributes
Theattributesofafiledeterminethekindsofoperations
thatcanmeaningfullybeappliedtothatfile.Moreover,they
dictatetosomeextentthecharacteristicsofthedataset
associatedwiththefile.Thefinaldeterminationoffile
attributestakesplacewhenthefileisopened,i.e.,associ
atedwithadataset.Ifafileisopenedandclosedseveral
times,itcanhavedifferentattributesatdifferentopenings.
ThefileattributesINPUT,OUTPUT,andUPDATEdetermine
thedirectionofinformationflowinanobviousway.Anopened
filemusthaveeithertheRECORDattributeortheSTREAM
attribute.Arecordfileisassociatedwithadatasetcon
sistingofasequenceofrecords,whicharereadorwritten
assingleunits.Arecordmayormaynothaveakeyassoci
atedwithit.Ifitdoes,thenthefilehastheKEYED
attribute.Iftherecordsaresequenced,i.e.,thenotionof
"nextrecord"ismeaningful,thenthefilehastheSEQUENTIAL
attribute;otherwiseithastheDIRECTattribute.Adirect
fileisnecessarilykeyed,sincewithoutakeythereisno
waytodesignatearecordwithinthefile,whileasequential
filemayormaynotbekeyed.
Astreamfileisassociatedwithadatasetconsistingof
asequenceofcharacters.Withinthesequenceofcharacters,
linemarks,pagemarks,andcarriagereturnscanappear.A
linemarkmarksthebreakbetweenthecharactersontwosucces

122

sivelines(eitherinputoroutput).Apagemarkismeaningful
onlyforadatasetthatistobeprinted,andmarksthestart
ofanewpage.Acarriagereturnismeaningfulonlyfora
datasetthatistobeprinted,andindicatesthatthefollow
inglineistobeoverprinted,i.e.,printedwithoutadvancing
thecarriage.Afileassociatedwithadatasettobeprinted
hasthePRINTattribute,andconsequentlytheOUTPUTattribute
also.
AfilemayalsohaveanENVIRONMENTattributeassociated
withit.TheENVIRONMENTattributecontainsimplementation
definedinformationdescribingtheassociateddataset.Typical
itemsfoundintheENVIRONMENTattributearerecordlength,
blockingfactors,recordformats,charactersetselection,and
tapedensities.
FileOpeningandAttributeDetermination
Afilecanbeopenedeitherexplicitly,throughexecution
ofanOPENstatement,orimplicitly,throughexecutionofsome
otherinputoutputstatementreferencinganunopenedfile.When
thefileisopened,anyattributesgiveninthefiledeclara
tionarecombinedwiththosegivenintheOPENstatement.The
resultingpartialsetofattributesisthencheckedforconsis
tency.Ifanyinconsistencyisfound,theUNDEFINEDFILE
conditionisraisedforthefile.Thendefaultingrulesare
appliedtogenerateacompletesetoffileattributes.The
possiblesetsoffileattributesaregiveninTable8.For

123

TABLE8.CompleteSetsofFileAttributes

STREAMINPUTFILE
STREAMOUTPUTFILE
STREAMOUTPUTPRINTFILE
STREAMINPUTSEQUENTIALFILE
RECORDINPUTSEQUENTIALKEYEDFILE
RECORDINPUTDIRECTKEYEDFILE
RECORDOUTPUTSEQUENTIALFILE
RECORDOUTPUTSEQUENTIALKEYEDFILE
RECORDOUTPUTDIRECTKEYEDFILE
RECORDUPDATESEQUENTIALFILE
RECORDUPDATESEQUENTIALKEYEDFILE
RECORDUPDATEDIRECTKEYEDFILE
Note:

TheENVIRONMENTattributemaybeadded
toanyofthesecombinations.

124

example,inthesequence
DECLARECHANGESINPUTFILE;
...
OPENFILE(CHANGES)KEYED;
theinitialsetofattributesusedforopeningthefileCHANGES
isINPUTKEYED.Sincetheseattributesareconsistentwith
eachother,theopeningcanproceed.TheRECORDandFILE
attributesareimpliedbytheKEYEDattribute,andsothese
areaddedtoobtainthesetRECORDINPUTKEYEDFILE.Although
bothDIRECTandSEQUENTIALareconsistentwiththisset,the
defaultchoiceisSEQUENTIAL,andsoSEQUENTIALisaddedto
obtainthecompleteset
RECORDINPUTSEQUENTIALKEYEDFILE
TheFILEoptioninanOPENstatementcontainsafilevalued
expression,whichiseitheraconstantorsomethingthat
evaluatestoafileconstant.Itisassumedthateachdataset
hasaname(typically,knowntothesurroundingoperating
system)andsothefileopeninghastospecifythenameofthe
datasettobelinkedtothefile.Thenamecanbespecified
byaTITLEoption;ifitisnot,thenameofthefileconstant
obtainedbyevaluatingtheFILEoptionisused.Thusthe
statements
DECLARECHANGENAMECHARACTER(4);
CHANGENAME='C437';
OPENFILE(CHANGES)TITLE(CHANGENAME)STREAMINPUT;
OPENFILE(OLDSET)RECORDINPUTDIRECT;
causethefileCHANGEStobeassociatedwiththedatasetC437,
andcausethefileOLDSETtobeassociatedwiththedatasetOLDSET.

125

Forstreamfiles,otherinformationcanbegiveninthe
OPENstatement.Forinstance,
OPENFILE(LISTING)PRINTLINESIZE(110)TAB(10,40,70)
PAGESIZE(50);
causesthefileLISTINGtobeopenedwiththeunderstanding
thatanewlinewillbestartedafteratmost110characters,
anewpagewillbestartedafteratmost50lines,andtabstops
(discussedunder"EditDirectedInputOutput"below)willbe
placedatcolumnpositions10,40,and70.Wereanyofthese
valuestobeomitted,implementationdefinedvalueswouldbe
assumed.
Ifaninputoutputstatementisexecutedonaclosedfile,
thenthefileisimplicitlyopened.Forinstance,ifthe
statement
PUTFILE(ANS)(M,N);
isexecutedandthefileANSisnotopen,thefilewillbe
openedwiththeimplicitattributesSTREAMandOUTPUT.
Similarly,ifthestatement
DELETEFILE(INV)KEY(PART_NAME);
isexecutedandthefileINVisnotopen,itwillbeopenedwith
theimplicitattributesRECORDandUPDATE.Theimplicitattri
butesaretreatedasthoughtheyappearedonanOPENstatement,
soanyattributesgiveninthedeclarationofthefileare
combinedwiththosederivedfromtheimplicitopening.

126

FileClosing
JustastheOPENstatementcreatestheconnectionbetween
afileandadataset,theCLOSEstatementbreakstheconnection.
Allfilesareautomaticallyclosedatprogramtermination.The
programmercanalsospecifyactionssuchasdatasetdisposition
bymeansofanENVIRONMENTattributeattachedtotheCLOSE
statement,e.g.,
CLOSEFILE(BIBLIO)ENVIRONMENT(REWIND);
Afilecanbeclosedandlaterreopenedwithdifferentattributes
Anattempttoopenafilethatisalreadyopen,ortoclosea
filethatisclosed,hasnoeffect.
OperationsonRecordFiles
Therearefivestatementsapplicabletorecordfiles:
READ
WRITE
LOCATE
REWRITE
DELETE
Eachofthese,inturn,hasanumberofclausesthatcanbe
appliedtoit.Theattributesofafiledeterminewhichstate
mentsandclausescanmeaningfullybeappliedtothatfile.
Forinstance,READcannotbeappliedtoanoutputfile,DELETE
canonlybeappliedtoanupdatefile,andanyclausethat
referencesakeycanonlybeappliedtoakeyedfile.The
meaningsofthestatementsaresummarizedinTable9,andthe
meaningsoftheclausesaresummarizedinTable10.Table11

127

Table9.RecordInputOutputStatement
READ

readarecordfromadataset(inputandupdatefilesonly

REWRITE

replacearecordonadataset
(updatefilesonly)

WRITE

addarecordtoadataset
(outputandupdatefilesonly)

LOCATE

obtainbufferspaceforarecord
(outputfilesonly)

DELETE

deletearecordfromadataset
(updatefilesonly)

Table10.ClausesonRecordInputOutputStatements
FILE

specifiesthefileaccessedbythisstatement

INTO

specifiesthegenerationtoreceivearecord
beingread

FROM

specifiesthegenerationcontainingarecord
tobewritten

KEY

specifiesarecordtoberead,replaced,
ordeleted

KEYFROM

specifiesthesourceforakeytobeattached
toarecordtobewritten

KEYTO

specifieswheretoputthekeyassociated
witharecordbeingread

IGNORE

specifiesthenumberofrecordstobeskipped
byexecutionofareadstatement

SET

specifieswheretoputapointertoanewly
createdgeneration

128

129

showshowthedifferentstatementformsrelatetothe
differentcombinationsoffileattributes.
Thechiefcharacteristicofrecordinputoutputis
thatitinvolvesadirecttransferofinformationbetween
thedatasetandaddressablememory,withoutanyformatting
orediting.Itisthereforetheprogrammer'sresponsibility
tobesurethattheformatofinformationonthedataset
agreeswiththeformatinmemory,asdefinedbytheimple
mentation.IfthedatasetisitselfcreatedbyaPL/Ipro
gram,thisisnottoodifficult.
TheREADstatementcausesasinglerecordtoberead
fromaspecifiedfile.Itcanalsobeusedtoskiprecords
onasequentialfile.Itssimplestform,appliedtoa
sequentialfile,isillustratedby
READFILE(CUST)INTO(CUST_INFO);
Asinglerecordistransferredfromthedatasetassociated
withCUSTintothevariableCUST_INFO.Ifthesizeofthe
recorddisagreeswiththesizeofthevariable,theRECORD
conditionisraisedforthefile.Iftherearenomorerecords
leftinthedataset,theENDFILEconditionisraisedforthe
file.
Thedestinationofanewlyreadrecordcanbespecified
eitherbyanINTOclauseorbyaSETclause.IftheINTO
clauseisgiven,thentherecordisreadintoabuffer,and
thepointerspecifiedintheSETclauseissettothelocation
oftherecordwithinthebuffer.AlthoughtheSETclauseis

130

lessconvenienttousethantheINTOclause,ithastwo
advantages.First,theSETclausecanbeusedtoread
recordswhoselengthisspecifiedwithintherecorditself.
TheINTOclausecannotbeusedforsuchrecordsbecausethe
sizeofthenecessaryvariableisnotknown.Second,operat
ingontherecordinthebufferavoidstheneedtocopy
therecordfromthebuffertothevariable.
TheKEYclauseisusedtospecifythepositionwithin
thedatasetoftherecordtoberead.Forinstance,the
statement
READFILE(EMPL)INTO(EMPLOYEE_RECORD)KEY(EMP_NUMBER);
causestherecordwhosekeyisthecharacterstringformof
EMP_NUMBERtobereadintothevariableEMPLOYEE_RECORD.
(Ifthekeyvalueisnotacharacterstring,itisconverted
toone.)Ifthekeydesignatesanonexistentrecord,theKEY
conditionisraisedforthefile.
TheKEYTOclause,incontrast,doesnotinfluencethe
datasetpositionatall.Insteadthekeyintherecordbeing
readisassignedtothevariablespecifiedintheKEYTOclause.
Thisfacilityisnecessarysincethekeymaynotbepartof
therecorditself.Forinstance,thestatement
READFILE(EMPL)INTO(EMPLOYEE_RECORD)KEYTO(EMP_NUMBER);
causesthenextrecordfromEMPL(whichmustbekeyedsequential)
tobereadintoEMPLOYEE_RECORD,andthekeyassociatedwith
thatrecordtobeassignedtoEMPNUMBER.

131

TheIGNOREclausecanbeusedinordertoskiprecords.
Forinstance,thestatement
READFILE(EMPL)IGNORE(2);
causestworecordsonthedatasetassociatedwithEMPLtobe
skipped.(EMPLmustnecessarilybesequential.)TheIGNORE
clauseandtheKEYclausecanbeusedtogether,andifthe
countintheIGNOREclauseiszerotheeffectistoposition
thedatasetattherecorddesignatedbytheKEYclause.The
IGNOREclauseandtheKEYTOclausecanbeusedtogetherto
readakeywithoutreadingtheassociatedrecord.
TheWRITEstatementcanbeusedonlywithoutputordirect
updatefiles.ItcausesthevariablenamedintheFROMclause
tobewrittenontothedataset.Ifthedatasetissequential,
thenewrecordiswrittenatitsend;otherwisetheposition
ofthenewrecordisarbitrary.TheKEYFROMclause,which
specifiesthekeyofthenewrecord,mustbeusedifthefile
iskeyed.
TheLOCATEstatementcanbeusedonlywithoutputfiles.
ItisanalogoustotheREADstatementwiththeSEToption.
ExecutionofaLOCATEstatementcausesspaceforthevariable
namedinthestatementtobeallocatedinanoutputbuffer,
andthencausesthepointernamedintheSETclausetobeset
tothelocationofthisspace.Ifthevariableisdeclared
withapointer,thentheSETclausecanbeomittedandthe
pointerobtainedfromthedeclarationwillbeused.For
instance,giventhestatements

132

DECLARERECSPACECHARACTER(200)BASED(CHPTR);
DECLARECHPTRPOINTER;
thestatements
LOCATERECSPACEFILE(NEWSET);
and
LOCATERECSPACEFILE(NEWSET)SET(CHPTR);
areequivalent.AfterexecutionofaLOCATEstatement,the
programmercanconstructarecordwithinthebuffer,referenc
ingtherecordusingthevariableandpointerspecifiedin
theLOCATEstatement.Therecordiswrittenwheneither
anotherLOCATEstatementoraWRITEstatementisexecuted
forthefile.ClosingthefileafterexecutingtheLOCATE
statementalsocausestherecordtobewritten.
TheREWRITEstatementcanonlybeusedwithupdatefiles;
itcausesarecordinthedatasettobereplaced.TheFROM
optioncanbeomittediftheprecedingoperationonthefile
wasaREADwiththeSETclause;inthiscasetherecordjust
read(whichisassumedtohavebeenmodified)replacesitsold
copyinthedataset.OtherwisetheFROMclausespecifiesthe
sourceofthereplacementrecord,andtheKEYclause,ifgiven,
specifieswhichrecordistobereplaced.IftheKEYclause
isnotgiven,thenthefilemustbesequential,andtherecord
atthecurrentpositioninthefileisreplaced.Forthe
replacementtobeacceptable,thecurrentpositionmustbe
welldefined,andtheprecedingoperationonthefilemustnot
havebeenaDELETE.

133

TheDELETEstatement,liketheREWRITEstatement,canonly
beusedwithupdatefiles.Ifakeyisspecified,thenthe
recordwiththatkeyisdeleted.Otherwisethebehavioris
similartothatofREWRITE:therecordatthecurrentposition
isdeleted;thecurrentpositionmustbewelldefined;andthe
precedingoperationmustnothavebeenanotherDELETE.

134

STREAMINPUTOUTPUT
Streaminputoutputdiffersfromrecordinputoutputin
thatatransformationisperformedwheninformationismoved
betweenagenerationofstorageandadataset.Onoutput,the
transformationconsistsoftranslatingadatavalue(which
mustbeofaprintabletype)intoacharacterrepresentation
ofthatvalue;oninput,thetransformationgoesintheopposite
direction.Thecharacterrepresentationneednotrepresent
thevaluedirectly,sinceformattingconventionscanbeused.
Forinstance,thecharactersequence"4387"couldrepresent
thevalue43.87oneitherinputoroutput,wereanappropriate
formattobeused.TheGETstatementisusedforstream
input,whilethePUTstatementisusedforstreamoutput.
Eachofthesestatementshasthreevariants:listdirected,
datadirected,andeditdirected.Withtheexceptionofafew
pathologicalcases,inputistheinverseofoutput.Thus,if
informationiswrittenbyaPUTstatementandlaterreadbya
GETstatementofthesameform,theoriginalvaluesinstorage
willbeunchanged.However,itisnotingeneraltruethat
readingfromafileandthenwritingwhatwasreadwillyield
thecontentsoftheoriginalfile.
ThefiletobeoperatedonbyaGETstatementoraPUT
statementcanbespecifiedeitherexplicitlyorimplicitly.
Thestatement
PUTFILE(TABLES)LIST(A,B);
causestheprintablerepresentationofthevaluesofAandB

135

tobewrittenontothefileTABLES.IftheFILEclauseis
omitted,thestandardinputfileSYSINisassumedforGET
statements,andthestandardoutputfileSYSPRINT(aprint
file)isassumedforPUTstatements.
Thestreaminputoutputstatementscanbeusedtoencode
anddecodestringsinstoragebymeansoftheSTRINGclause.
Forexample,thestatement
GETSTRING(STR)LIST(A,B);
causesthevaluesofthevariablesAandBtobe"read"from
thestringSTR,justasthoughSTRwasasequenceofcharacters
onaninputfile.Similarly,
PUTSTRING(STR)LIST(A,B);
causesthevaluesofAandBtobeconvertedtotheirprintable
representations,andthencausesthesequenceofrepresentations
(withaninterveningblank)tobeassignedtothecharacter
variableSTR.
LineandpageskipscanbespecifiedintheGETstatement
andthePUTstatement,althoughcertainformsareapplicable
onlytoaPUTstatementthatdesignatesaprintfile.For
instance,
PUTSKIP(2)LIST(A,B);
causestwolinestobeskippedbeforeAandBareprinted,while
PUTPAGELIST(A,B);
causesanewpagetobestartedbeforeAandBareprinted.
Thestatement

136

PUTLINE(2)LIST(A,B);
causestheprintertobepositionedtothesecondlineonthe
pagebeforeAandBareprinted;itdiffersfromSKIPinthat
itselectsanabsolutepagepositionratherthanapageposi
tionrelativetothepreviousline.PAGEandLINEcanonly
bespecifiedforprintfiles.SKIPonaninputfilecauses
theremainderoftheinputlinetobeskipped.
DataLists
AGETstatementoraPUTstatementcancontainoneor
moredatalists,specifyingtheitemstobereadorwritten.
Initssimplestform,thedatalistismerelyasequenceof
scalars,e.g.
PUTLIST(RATE,TIME,RATE*TIME);
Asthisexampleshows,expressionsaswellasvariablescan
appearinthedatalistofaPUTstatement.Theitemsin
thedatalistofaGETstatement,however,havethesame
restrictionsasthetargetsofanassignmentstatement,since
onecannotreadavalueintoanexpression.Adatalistcan
alsocontainiterations,e.g.,
PUTLIST((I,F(I)DOI=1TOFNLIMIT));
Sinceanyitemcanitselfbeaniteration,iterationscanbe
nestedtoanydepth.TheDOthatcontrolsthestatementis
subjecttothesamerestrictionsasthespecifiedDOstatement.
AGETstatementcanuseaninputvalueasaniteration
count,e.g.,

137

GETLIST((N,(COST(K)DOK=1TON));
Moreover,aggregatescanbeincludedinthedatalist,e.g.,
DECLAREMIX(40,40)FIXED;
PUTLIST((MIX(*,I)DOI=1TO40));
InthisexampletheelementsofMIXwillbeprintedoutwith
thefirstsubscriptvaryingmostrapidly,asinFortran.On
theotherhand,thestatement
PUTLIST(MIX);
withMIXdeclaredasabovewillprintouttheelementsofMIX
withthelastsubscriptvaryingmostrapidly(sincethisisthe
implicitorderinstorage,asdefinedbytherulesofPL/I).

ListDirectedInputOutput
TheGETLISTstatementreadsanunformattedsequenceof
itemsfromtheinputstream.Thedatatobereadconsistsof
alistofitemsseparatedbyblanksorcommas,e.g.,
23,47,'DAVIDDAVIS'
Sincethedatasetisleftpositionedafterthelastcharacter
thatwasread,itispossibletoreaditemsfromthesameline
usingseveralseparateGETLISTstatementsinsuccession.The
successiveitemsonthedatasetareassignedtothesuccessive
itemsinthedatalist.Ifthedatalistcontainsanaggregate,
thenenoughitemsarereadfromthedatasettofilltheaggre
gate.Thedatasetcanalsoindicateemptyitemsbymeansof
twocommasinarow.Forinstance,thestatement

138

GETLIST(M1,M2,M3);
appliedtotheinput
22,,891
willcauseMltobesetto22,M3tobesetto891,andM2to
beleftunchanged.
Thetypesoftheitemsreadfromthedatasetneednot
agreewiththetypesoftheitemsinthedatalist;ifthere
isanydisagreement,theitemreadisconvertedtothetype
oftheiteminthedatalist.Forinstance,theinputvalue
forafloatvariablecanbewrittenasaninteger.A
characterstringitemonthedatasetneednotbequoted
unlessitcontainsacommaorblankorstartswithaquote.
Thus
THISISN'TBAD
canbereadintoalistofthreecharactervariables,andthe
variableswillreceivethestringsexactlyaswritten.
However,ifthedatasetcontainstheitem
'ISN''T'
theusualrulesforinterpretingacharacterstringconstant
willbeappliedandthereceivingvariableswillreceivethe
value
ISN'T
ThePUTLISTstatementwritesasequenceofitemsonto
thespecifiedoutputfile.Successiveitemsareplacedat
successivetabstoppositions,andwhenalineisfilled(as

139

definedbythelinesizeforthedataset)anewlineis
started.Iftheoutputfileisnotaprintfile,however,
itemsareseparatedbysingleblanksratherthanplacedat
tabstops.Thustheeffectof
PUTSKIPLIST((NDOI=1TO10));
mightbetoprintthelines
1

10

undersomeappropriateassumptionsaboutthelinesizeand
tabstoppositions.SinceaPUTLISTstatementdoesnotforce
anendofline,severalPUTLISTstatementscanplaceoutput
ontothesameline.

DataDirectedInputOutput
TheGETDATAstatementreadsasequenceofvariablenames
andassociatedvalues,e.g.,
A=3

B=12 D=0;

Thepairsinthissequencecanbeseparatedbyeitherblanks
orcommas(aswiththeGETLISTstatement),andthesequenceis
endedbyasemicolon.TheGETDATAstatementitselfcan,but
neednot,specifyalistofvariables,e.g.,
GETDATA(A,B,C,D,E);
or
GETDATA;
Thesecondformiseasiertouse,butithasthedisadvantage

140

thatitforcesacompletesymboltabletobeincludedinthe
compiledprogram.Theitemsintheinputstreamneednotbe
giveninthesameorderasthevariablesinthelist.More
over,variablesinthedatalistcanberepeatedoromitted
intheinputstream.Subscriptedandnamequalifiedvariables
canalsobeincludedintheinputstream,althoughname
qualificationsmustbecomplete.Forinstance,
A(3,7)='JOE',A(4,7)='SAM',ST.COUV=19.3;
isavalidinputline,assuminganappropriatedatalist.
ThePUTDATAstatementwritesalistofvariables,
togetherwiththeirvalues,ontotheoutputstream.Aswith
theGETDATAstatement,thePUTDATAstatementneednot
containalist.Executionofthestatement
PUTDATA;
causesthevaluesofallprintablevariablestobewritten
ontotheoutputstream.Otherwise,thelistedvariables
arewrittenout.Ifanyofthesevariablesareaggregates,
thescalarelementsoftheaggregatearewrittenout,
usingfullyqualifiednamesandappropriatesubscripts.
UnliketheothertwoformsofthePUTstatement,the
PUTDATAstatementcannotincludeexpressionsinthedata
list,sinceexpressionsdonothavenames.Iftheoutput
fileisaprintfile,successiveitemsareplacedatsucces
sivetabstops.Thus,assumingappropriatestoredvaluesand
tabstops,theeffectofthestatements

141

DECLARE
1AGG(3),
2(RED,BLUE)FIXEDDECIMAL(2);
PUTDATA(AGG);
istoprintoutthelines
AGG.RED(l)=4
AGG.BLUE(2)=5

AGG.BLUE(l)=8
AGG.RED(3)=7

AGG.RED(2)=0
AGG.BLUE(3)=1;

EditDirectedInputOutput
Editdirectedinputoutputisaccomplishedthroughthe
GETandPUTEDITstatements.Foreditdirectedinputoutput,
thetransformationbetweentheinternalandexternalforms
ofthedataisgovernedbyaformatlist.Whenanitemin
adatalistisread,aformatisobtainedfromtheformat
listandusedtotransformthecharacterrepresentationof
theitem,asitappearsintheinputstream,intoastored
value.Whenaniteminadatalistiswritten,aformatis
usedtotransformthevalueoftheitemintoasequenceof
characterstobeinsertedintotheoutputstream.Forexample,
thestatement
GETEDIT(I,J)(F(4),F(3));
appliedtotheinputstream
25.003.14
causesthevariablesIandJtobeassignedthevalues15
(obtainedfromthefirstfourcharactersofthestream)and
3(obtainedfromthenextthreecharactersofthestream).
Similarly,

142

PUTEDIT(25,3.142)(2F(7,2));
causesthecharacters
25.003.14
tobeplacedintotheoutputstream.Inthiscase,the2in
frontoftheformatitemF(7,2)indicatesthattheitemis
toberepeatedtwice.

TheavailableformatsarelistedinTable12.There
aretwokindsofformats:controlformatsanddataformats.
Controlformatscontrolpositioningofthedataset;they
causeskippingofinformationoninput,andgenerationof
blanks,linemarks,pagemarks,andcarriagereturnsonoutput.
Whenaformatlistisinterpreted,controlformatsareexecuted
astheyareencountered;acontrolformatdoesnotuseupan
itemfromthedatalist.Adataformat,ontheotherhand,
requiresacorrespondingiteminthedatalist,andthe
formatitemtogetherwiththedataitemdetermineswhataction
istobetaken.

Whenthedatalistisexhausted,interpretationofthe
formatlistceases.Forinstance,executionofthestatement
PUTEDIT(J)(E(9),SKIP);
doesnotcausethecontrolformatSKIPtobeexecuted,since
afterJispairedwithE(9)thedatalistisexhaustedand
executionofthestatementiscomplete.Iftheformatlist
isexhaustedwhileitemsstillremaininthedatalist,then
interpretationoftheformatliststartsoveragainfromthe

143

Table12.FormatTypes

(1)DataFormats
A(w)
B(w)
Bl(w)
B2(w)
B3(w)
B4(w)
F(w,d,s)
E(w,d,s)
Ppic
C(f1,f2)

(2)

alphanumericwithfieldwidthw
(wcanbeomittedonoutput)
bitstringwithfieldlengthw
(wcanbeomittedonoutput;
B1indicatesbase2,B2indicatesbase4,
B3indicatesbase8,and
B4indicatesbase16)
fixedwithfieldwidthw,ddigitstoright
ofdecimalpoint,scalings
(dandsareoptional)
floatwithfieldwidthw,ddigitstoright
ofdecimalpointinmantissa,sdigitsin
mantissa(dandsareoptional)
picturedaccordingtopicturepic
complexwithrealpartformattedusingfl,
imaginarypartformattedusingf2
(f2assumedthesameasfliff2omitted)

ControlFormats
X(w)

blankorignorefieldofwidthw

COLUMN(n)

continuereadingorwritingatcolumnpositionn

TAB(n)

skipntabstops

SKIP(n)

skipnlines

LINE(n)

positionatnthlineofprintedpage

PAGE

startnewprintedpage

(3)RemoteFormat
R(ref)

useformatobtainedbyevaluating
referenceref

144

Table13.ExamplesofInputFormats
InputField

Format

Value

TWOCATS

A(8)

TWOCATS

1011

B(4)

'1011'B

ONE

B(3)

noneCONVERSIONraised

1011

B(7)

'1011'B

2437

B3(4)

'010100011111'B

2437

F(4)

2437

2427

F(6)

2437

2437

F(6,1)

243.7

.2437

F(4,1)

.2437

2437

F(4,1,2)

24370

CATS

F(4,1,2)

noneCONVERSIONraised

2437E1

F(6)

noneCONVERSIONraised

2437

E(4)

2437E0

2437E2

E(7)

24.37E0

2437

E(4,1)

243.7E0

2437E2

E(4,1)

2.437E0

2.437E2

E(5,1)

243.7E0

2437E2

E(4,1,1)

2.437E0

F(3)

E(3)

2437

P'(6)Z'

2437

2437

P'(6)Z'

noneCONVERSIONraised

2437

C(F(2))

24+37I

2437

C(F(3,1),F(2))

2.4+37I

145

Table14.ExamplesofOutputFormats

Value

Format

OutputField

DYNASTY

DYNASTY

2.48

2.48

DYNASTY

A(6)

DYNAST

DYNASTY

A(10)

DYNASTY

'1011001'B

1011001

'1011001'B

B3

544

'1011001'B

B4

D2

'1011001'B

B4(5)

D2

'1011001'B

B4(1)

D(andSTRINGSIZEraised)

2.48

F(6)

2.48

F(6,1)

2.5

2.48

F(6,3,1)

0.248

25

F(2)

noneSIZEraised

24.86

E(13)

2.486E+001

24.86

E(13,0)

2486E002

24.86

E(13,1,3)

24.9E+000

2.48

P'$$$V,99'

$2.48

17.9+6I

C(F(6,1))

17.96.0

17.9+6I

C(F(6,1),F(6))

17.96

146

beginning.Forinstance,
DECLAREA(*)FLOAT;
PUTEDIT(A)(SKIP,6E(14,5));
causesthecontentsofthearrayAtobewrittenoutwith
sixvaluesonaline.Asmanylinesasnecessaryareused.
Aformatlistcancontainrepeateditemsandrepeated
lists.Therepetitioncountsandparametersinaformatlist
arenotlimitedtoconstants;theycanbearbitraryexpres
sions,asintheformatlist
((M)E(14,11K),(N)(A(L),X(5),A(L+1)))
Repetitioncountsthatarenotintegerconstantsmust
bewritteninparentheses.
Aneditdirectedstatementcanhavemorethanonepair
ofdatalistsandformatlists,e.g.
PUTEDIT(A(*,3))(SKIP,10E(14,DECPT))
(A(*,4))(SKIP,6E(14,DECPT);
Thebehaviorofinputformatsappliedtovariousdatavalues
isillustratedinTable13.ExceptforthePformatandthe
Cformat,alloftheinputformatsspecifyafieldwidth,
whichisthenumberofcharacterstobereadfromtheinput
stream.(ThePformatandCformatspecifythefieldwidth
implicitly.)FortheBformats,theEformat,andtheFformat,
thenumericalvaluetobereadcanhaveleadingandtrailing
blanks,whichareignored.Linemarkswithinafieldare
ignored,sothatafieldcanbesplitovertwolines.Forthe
FformatandtheEformat,thesecondparameter,ifpresent,

147

indicateswhereanimplicitdecimalpointshouldbeinserted
ifnoneappearsexplicitlyintheinput.FortheFformat,
thethirdparameterspecifiesscalingtobeappliedtothe
inputvalue,whilethethirdparameterofanEformatis
ignored.
ThebehaviorofoutputformatsisshowninTable14.
Theoutputformatshavebehaviorinversetotheinputformats.
Therulesarenotentirelyinverse,however,sincetheinput
formatsassignmeaningtocertainfieldsthatcannotbepro
ducedbythecorrespondingoutputformats.Forinstance,an
outputFformatcannotproducetrailingblanks,butaninput
Fformatcanreadtrailingblanks.Moreover,unscaledoutput
fieldsalwayshaveexplicitdecimalpointsunlesstheyare
integers,butunscaledinputfieldsmayhaveimplicitdecimal
points.Anotherdifferenceisthatonoutput,theAformat
andtheBformatsneednotcontainfieldwidths,sinceafield
widthcanbededucedbyconvertingtheoutputvaluetocharacter
typeortobittypeasappropriate.
Aremoteformatcanappearinaformatlist,eitheras
theonlyiteminthelistorincombinationwithotheritems.
TheformatitemR(ref)isinterpretedbyevaluatingthereference
ref,whichmustbeformatvalued,i.e.,itmustevaluatetothe
statementnameofaFORMATstatement.Thecontentsofthat
FORMATstatementaretheninterpreted.Forinstance,theeffect
ofthestatements
FF:

GETEDIT(A,B,C)(F(3),R(FF),F(2));
FORMAT(F(5));

148

isthesameasthatofthestatement
GETEDIT(A,B,C)(F(3),F(5),F(2));
Remoteformatsareusefulwhenthesameformatistobeused
inanumberofdifferentPUTEDITorGETEDITstatements.
Thesameformatcanbeusedforbothinputandoutput.

149

BIBLIOGRAPHY

1. AmericanNationalStandardsInstitute,"American
NationalStandardProgrammingLanguagePL/I,"
ReportANSIX3.531976,NewYork.
2. Beech,D.,AStructuralViewofPL/I,ACMComputing
Surveys(2)1,March1970,pp.3364.
3. Beech,D.,andMarcotty,M.,UnfurlingthePL/IStandard,
SIGPLANNotices(8)10,October1973,pp.1243.
4. Frieburghouse,R.,TheMULTICSPL/ICompiler,1969Fall
JointComputerConference(35),AFIPSPress,Montvale,
NewJersey,pp.187199.
5. HoneywellInformationSystems,Inc.,"PL/ILanguage
Manual,"Cambridge,Massachusetts,1974.
6. IBMCorporation,"PL/ILanguageSpecifications,"
NumberGY3360032,1970.
7. Lucas,P.,andK.Walk,OntheFormalDefinitionofPL/I,
AnnualReviewinAutomaticProgramming(6)3,1969,
PergamonPress,pp.105181.
8. Pollack,S.,andSterling,T.,"AGuidetoPL/I,"
SecondEdition,Holt,ReinhartandWinston,NewYork,1976
9. Radin,G.,andRogoway,H.,NPL:HighlightsofaNew
ProgrammingLanguage,CommunicationsoftheACM(8)1,
January1965,pp.917.

150

Thisreportwaspreparedasanaccountof
Governmentsponsoredwork.Neitherthe
UnitedStates,northeAdministration,
noranypersonactingonbehalfofthe
Administration:
A.Makesanywarrantyorrepresentation,
expressorimplied,withrespecttothe
accuracy,completeness,orusefulnessof
theinformationcontainedinthisreport,
orthattheuseofanyinformation,
apparatus,method,orprocessdisclosed
inthisreportmaynotinfringeprivately
ownedrights;or
B.Assumesanyliabilitieswithrespectto
theuseof,orfordamagesresultingfrom
theuseofanyinformation,apparatus,
method,orprocessdisclosedinthis
report.
Asusedintheabove,"personactingonbehalf
oftheAdministration"Includesanyemployee
orcontractoroftheAdministration,or
employeeofsuchcontractor,totheextent
thatsuchemployeeorcontractorofthe
Administration,oremployeeofsuchcontractor
prepares,disseminates,orprovidesaccessto,
anyinformationpursuanttohisemploymentor
contractwiththeAdministration,orhis
employmentwithsuchcontractor.

11

EDITORIAL NOTES
The material in this section is not part of the original publication, but was added by the editor in the
process of converting the document to a PDF.
For comments, corrections, etc. contact:
Peter_Flass (at) Yahoo (dot) com

Acknowledgement
Thanks are owed to the Internet Archive (www.archive.org) for hosting both the PDF (image) copy of
this publication, and also the OCR'd text, which proved remarkably accurate.
[http://www.archive.org/details/pliprogrammingla00abra]

Errata
Page 4
Page 5
Page 7
Page 18
Page 50
Page 51
Page 54

(Example 1) after THE J-TH LETTER., '/*' changed to '*/'.


Comment before 'GET_DIGRAM' changed '/*' to '*/ at end.
Changed keywrods to keywords in last paragraph.
pic 'z,zzz', val 1234, changed to result=1,234.
Changed comparision to comparison in last paragraph.
Changed conerted to converted in paragraph 2.
BIT(x,[le]) changed to BIT(x[,le]).
CEIL changed to read x must not be complex.
CHARACTER(sa,[le]) changed to CHARACTER(sa[,le]).
Page 59 VERIFY The name of the second argument 'ca' is unreadable.
Page.63 'ACON' changed ACOS.
Page 64.. VALID 'varible' should read 'variable'.
Page 67 OFFSET(P,AR) changed to relative to AR.
Page 74 previuosly changed to previously in first paragraph.
Page 76 convenient changed to inconvenient in paragraph 3.
Page 113 reevaluatd changed to reevaluated.
Page 116 Semicolon inserted between END and IF A(I).
Page 142 Comma after AGG(3).
Page 144 Fixed typos in 'C' format description.
Page 149 GED changed to GET in last paragraph.

NOTES-1

About the Author


Paul W. Abrahams, Sc.D., CCP, is the author of numerous computer books and articles. A
consulting computer scientist and past president of the Association for Computing Machinery, he
specializes in programming languages, design and implementation of software systems, and technical
writing. He received his bachelor's degree in mathematics from the Massachusetts Institute of
Technology in 1956 and his doctorate in mathematics there in 1963, studying artificial intelligence
under Marvin Minsky and John McCarthy and writing his dissertation on "Machine Verification of
Mathematical Proof". He is one of the designers of the first LISP system and also the designer of the
CIMS PL/I system, which he developed while a professor at New York University. He also
participated in the design of the Software Engineering Design Language (SEDL), developed at the IBM
T.J. Watson Laboratories. In 1995 he was honored as a Fellow of the ACM.

adapted from InformIT


http://www.informit.com/authors/bio.aspx?a=33D9A1DB-DAE1-4EC3-BAE5-406F84184012

NOTES-2

S-ar putea să vă placă și