Tải bản đầy đủ - 0 (trang)
Patterns, Actions, and Variables

Patterns, Actions, and Variables

Tải bản đầy đủ - 0trang

Chapter7.Patterns,Actions,and

Variables

Asyouhavealreadyseen,eachawkstatementconsistsofapatternwithanassociated

action.Thischapterdescribeshowyoubuildpatternsandactions,whatkindsofthings

youcandowithinactions,andawk’spredefinedvariables.

Thepattern–actionrulesandthestatementsavailableforusewithinactionsformthecore

ofawkprogramming.Inasense,everythingcovereduptoherehasbeenthefoundation

thatprogramsarebuiltontopof.Nowit’stimetostartbuildingsomethinguseful.



PatternElements

Patternsinawkcontroltheexecutionofrules—aruleisexecutedwhenitspattern

matchesthecurrentinputrecord.Thefollowingisasummaryofthetypesofawkpatterns:

/regularexpression/



Aregularexpression.Itmatcheswhenthetextoftheinputrecordfitstheregular

expression.(SeeChapter3.)

expression



Asingleexpression.Itmatcheswhenitsvalueisnonzero(ifanumber)ornon-null(ifa

string).(SeeExpressionsasPatterns.)

begpat,endpat



Apairofpatternsseparatedbyacomma,specifyingarangeofrecords.Therange

includesboththeinitialrecordthatmatchesbegpatandthefinalrecordthatmatches

endpat.(SeeSpecifyingRecordRangeswithPatterns.)

BEGIN

END



Specialpatternsforyoutosupplystartuporcleanupactionsforyourawkprogram.(See

TheBEGINandENDSpecialPatterns.)

BEGINFILE

ENDFILE



Specialpatternsforyoutosupplystartuporcleanupactionstobedoneonaper-file

basis.(SeeTheBEGINFILEandENDFILESpecialPatterns.)

empty



Theemptypatternmatcheseveryinputrecord.(SeeTheEmptyPattern.)



RegularExpressionsasPatterns

Regularexpressionsareoneofthefirstkindsofpatternspresentedinthisbook.Thiskind

ofpatternissimplyaregexpconstantinthepatternpartofarule.Itsmeaningis‘$0~

/pattern/’.Thepatternmatcheswhentheinputrecordmatchestheregexp.Forexample:

/foo|bar|baz/{buzzwords++}

END{printbuzzwords,"buzzwordsseen"}



ExpressionsasPatterns

Anyawkexpressionisvalidasanawkpattern.Thepatternmatchesiftheexpression’s

valueisnonzero(ifanumber)ornon-null(ifastring).Theexpressionisreevaluatedeach

timetheruleistestedagainstanewinputrecord.Iftheexpressionusesfieldssuchas$1,

thevaluedependsdirectlyonthenewinputrecord’stext;otherwise,itdependsononly

whathashappenedsofarintheexecutionoftheawkprogram.

Comparisonexpressions,usingthecomparisonoperatorsdescribedinVariableTypingand

ComparisonExpressions,areaverycommonkindofpattern.Regexpmatchingand

nonmatchingarealsoverycommonexpressions.Theleftoperandofthe‘~’and‘!~’

operatorsisastring.Therightoperandiseitheraconstantregularexpressionenclosedin



slashes(/regexp/),oranyexpressionwhosestringvalueisusedasadynamicregular

expression(seeUsingDynamicRegexps).Thefollowingexampleprintsthesecondfield

ofeachinputrecordwhosefirstfieldisprecisely‘li’:

$awk'$1=="li"{print$2}'mail-list



(Thereisnooutput,becausethereisnopersonwiththeexactname‘li’.)Contrastthis

withthefollowingregularexpressionmatch,whichacceptsanyrecordwithafirstfield

thatcontains‘li’:

$awk'$1~/li/{print$2}'mail-list

555-5553

555-6699



Aregexpconstantasapatternisalsoaspecialcaseofanexpressionpattern.The

expression/li/hasthevalueoneif‘li’appearsinthecurrentinputrecord.Thus,asa

pattern,/li/matchesanyrecordcontaining‘li’.

Booleanexpressionsarealsocommonlyusedaspatterns.Whetherthepatternmatchesan

inputrecorddependsonwhetheritssubexpressionsmatch.Forexample,thefollowing

commandprintsalltherecordsinmail-listthatcontainboth‘edu’and‘li’:

$awk'/edu/&&/li/'mail-list

Samuel555-3430samuel.lanceolis@shu.eduA



Thefollowingcommandprintsallrecordsinmail-listthatcontaineither‘edu’or‘li’

(orboth,ofcourse):

$awk'/edu/||/li/'mail-list

Amelia555-5553amelia.zodiacusque@gmail.comF

Broderick555-0542broderick.aliquotiens@yahoo.comR

Fabius555-1234fabius.undevicesimus@ucb.eduF

Julie555-6699julie.perscrutabor@skeeve.comF

Samuel555-3430samuel.lanceolis@shu.eduA

Jean-Paul555-2127jeanpaul.campanorum@nyu.eduR



Thefollowingcommandprintsallrecordsinmail-listthatdonotcontainthestring‘li’:

$awk'!/li/'mail-list

Anthony555-3412anthony.asserturo@hotmail.comA

Becky555-7685becky.algebrarum@gmail.comA

Bill555-1675bill.drowning@hotmail.comA

Camilla555-2912camilla.infusarum@skynet.beR

Fabius555-1234fabius.undevicesimus@ucb.eduF

Martin555-6480martin.codicibus@hotmail.comA

Jean-Paul555-2127jeanpaul.campanorum@nyu.eduR



ThesubexpressionsofaBooleanoperatorinapatterncanbeconstantregularexpressions,

comparisons,oranyotherawkexpressions.Rangepatternsarenotexpressions,sothey

cannotappearinsideBooleanpatterns.Likewise,thespecialpatternsBEGIN,END,

BEGINFILE,andENDFILE,whichnevermatchanyinputrecord,arenotexpressionsand

cannotappearinsideBooleanpatterns.

Theprecedenceofthedifferentoperatorsthatcanappearinpatternsisdescribedin

OperatorPrecedence(HowOperatorsNest).



SpecifyingRecordRangeswithPatterns

Arangepatternismadeoftwopatternsseparatedbyacomma,intheform‘begpat,

endpat’.Itisusedtomatchrangesofconsecutiveinputrecords.Thefirstpattern,begpat,

controlswheretherangebegins,whileendpatcontrolswherethepatternends.For

example,thefollowing:



awk'$1=="on",$1=="off"'myfile



printseveryrecordinmyfilebetween‘on’/‘off’pairs,inclusive.

Arangepatternstartsoutbymatchingbegpatagainsteveryinputrecord.Whenarecord

matchesbegpat,therangepatternisturnedon,andtherangepatternmatchesthisrecord

aswell.Aslongastherangepatternstaysturnedon,itautomaticallymatcheseveryinput

recordread.Therangepatternalsomatchesendpatagainsteveryinputrecord;whenthis

succeeds,therangepatternisturnedoffagainforthefollowingrecord.Thentherange

patterngoesbacktocheckingbegpatagainsteachrecord.

Therecordthatturnsontherangepatternandtheonethatturnsitoffbothmatchtherange

pattern.Ifyoudon’twanttooperateontheserecords,youcanwriteifstatementsinthe

rule’sactiontodistinguishthemfromtherecordsyouareinterestedin.

Itispossibleforapatterntobeturnedonandoffbythesamerecord.Iftherecordsatisfies

bothconditions,thentheactionisexecutedforjustthatrecord.Forexample,suppose

thereistextbetweentwoidenticalmarkers(e.g.,the‘%’symbol),eachonitsownline,that

shouldbeignored.Afirstattemptwouldbetocombinearangepatternthatdescribesthe

delimitedtextwiththenextstatement(notdiscussedyet,seeThenextStatement).This

causesawktoskipanyfurtherprocessingofthecurrentrecordandstartoveragainwith

thenextinputrecord.Suchaprogramlookslikethis:

/^%$/,/^%$/{next}

{print}



Thisprogramfailsbecausetherangepatternisbothturnedonandturnedoffbythefirst

line,whichjusthasa‘%’onit.Toaccomplishthistask,writetheprograminthefollowing

manner,usingaflag:

/^%$/{skip=!skip;next}

skip==1{next}#skiplineswith`skip'set



Inarangepattern,thecomma(‘,’)hasthelowestprecedenceofalltheoperators(i.e.,itis

evaluatedlast).Thus,thefollowingprogramattemptstocombinearangepatternwith

another,simplertest:

echoYes|awk'/1/,/2/||/Yes/'



Theintentofthisprogramis‘(/1/,/2/)||/Yes/’.However,awkinterpretsthisas‘/1/,

(/2/||/Yes/)’.Thiscannotbechangedorworkedaround;rangepatternsdonot

combinewithotherpatterns:

$echoYes|gawk'(/1/,/2/)||/Yes/'

error→gawk:cmd.line:1:(/1/,/2/)||/Yes/

error→gawk:cmd.line:1:^syntaxerror



Asaminorpointofinterest,althoughitispoorstyle,POSIXallowsyoutoputanewline

afterthecommainarangepattern.(d.c.)



TheBEGINandENDSpecialPatterns

Allthepatternsdescribedsofarareformatchinginputrecords.TheBEGINandENDspecial

patternsaredifferent.Theysupplystartupandcleanupactionsforawkprograms.BEGIN

andENDrulesmusthaveactions;thereisnodefaultactionfortheserulesbecausethereis

nocurrentrecordwhentheyrun.BEGINandENDrulesareoftenreferredtoas“BEGINand

ENDblocks”bylongtimeawkprogrammers.



Startupandcleanupactions

ABEGINruleisexecutedonceonly,beforethefirstinputrecordisread.Likewise,anEND

ruleisexecutedonceonly,afteralltheinputisread.Forexample:

$awk'

>BEGIN{print"Analysisof\"li\""}

>/li/{++n}

>END{print"\"li\"appearsin",n,"records."}'mail-list

Analysisof"li"

"li"appearsin4records.



Thisprogramfindsthenumberofrecordsintheinputfilemail-listthatcontainthe

string‘li’.TheBEGINruleprintsatitleforthereport.ThereisnoneedtousetheBEGIN

ruletoinitializethecounterntozero,asawkdoesthisautomatically(seeVariables).The

secondruleincrementsthevariableneverytimearecordcontainingthepattern‘li’is

read.TheENDruleprintsthevalueofnattheendoftherun.

ThespecialpatternsBEGINandENDcannotbeusedinrangesorwithBooleanoperators

(indeed,theycannotbeusedwithanyoperators).Anawkprogrammayhavemultiple

BEGINand/orENDrules.Theyareexecutedintheorderinwhichtheyappear:alltheBEGIN

rulesatstartupandalltheENDrulesattermination.BEGINandENDrulesmaybeintermixed

withotherrules.Thisfeaturewasaddedinthe1987versionofawkandisincludedinthe

POSIXstandard.Theoriginal(1978)versionofawkrequiredtheBEGINruletobeplaced

atthebeginningoftheprogram,theENDruletobeplacedattheend,andonlyallowedone

ofeach.Thisisnolongerrequired,butitisagoodideatofollowthistemplateintermsof

programorganizationandreadability.

MultipleBEGINandENDrulesareusefulforwritinglibraryfunctions,becauseeachlibrary

filecanhaveitsownBEGINand/orENDruletodoitsowninitializationand/orcleanup.The

orderinwhichlibraryfunctionsarenamedonthecommandlinecontrolstheorderin

whichtheirBEGINandENDrulesareexecuted.Therefore,youhavetobecarefulwhen

writingsuchrulesinlibraryfilessothattheorderinwhichtheyareexecuteddoesn’t

matter.SeeCommand-LineOptionsformoreinformationonusinglibraryfunctions.See

Chapter10foranumberofusefullibraryfunctions.

IfanawkprogramhasonlyBEGINrulesandnootherrules,thentheprogramexitsafterthe

BEGINrulesarerun.[34]However,ifanENDruleexists,thentheinputisread,evenifthere

arenootherrulesintheprogram.ThisisnecessaryincasetheENDrulecheckstheFNRand

NRvariables.

Input/outputfromBEGINandENDrules

Thereareseveral(sometimessubtle)pointstobeawareofwhendoingI/OfromaBEGIN

orENDrule.Thefirsthastodowiththevalueof$0inaBEGINrule.BecauseBEGINrules

areexecutedbeforeanyinputisread,theresimplyisnoinputrecord,andthereforeno

fields,whenexecutingBEGINrules.Referencesto$0andthefieldsyieldanullstringor

zero,dependinguponthecontext.Onewaytogive$0arealvalueistoexecuteagetline

commandwithoutavariable(seeExplicitInputwithgetline).Anotherwayissimplyto

assignavalueto$0.

Thesecondpointissimilartothefirst,butfromtheotherdirection.Traditionally,due

largelytoimplementationissues,$0andNFwereundefinedinsideanENDrule.ThePOSIX



standardspecifiesthatNFisavailableinanENDrule.Itcontainsthenumberoffieldsfrom

thelastinputrecord.Mostprobablyduetoanoversight,thestandarddoesnotsaythat$0

isalsopreserved,althoughlogicallyonewouldthinkthatitshouldbe.Infact,allofBWK

awk,mawk,andgawkpreservethevalueof$0foruseinENDrules.Beaware,however,that

someotherimplementationsandmanyolderversionsofUnixawkdonot.

Thethirdpointfollowsfromthefirsttwo.Themeaningof‘print’insideaBEGINorEND

ruleisthesameasalways:‘print$0’.If$0isthenullstring,thenthisprintsanempty

record.Manylongtimeawkprogrammersuseanunadorned‘print’inBEGINandEND

rules,tomean‘print""’,relyingon$0beingnull.Althoughonemightgenerallyget

awaywiththisinBEGINrules,itisaverybadideainENDrules,atleastingawk.Itisalso

poorstyle,becauseifanemptylineisneededintheoutput,theprogramshouldprintone

explicitly.

Finally,thenextandnextfilestatementsarenotallowedinaBEGINrule,becausethe

implicitread-a-record-and-match-against-the-rulesloophasnotstartedyet.Similarly,

thosestatementsarenotvalidinanENDrule,becausealltheinputhasbeenread.(SeeThe

nextStatementandThenextfileStatement.)



TheBEGINFILEandENDFILESpecialPatterns

Thissectiondescribesagawk-specificfeature.

Twospecialkindsofrule,BEGINFILEandENDFILE,giveyou“hooks”intogawk’s

command-linefileprocessingloop.AswiththeBEGINandENDrules(seetheprevious

section),allBEGINFILErulesinaprogramaremerged,intheordertheyarereadbygawk,

andallENDFILErulesaremergedaswell.

ThebodyoftheBEGINFILErulesisexecutedjustbeforegawkreadsthefirstrecordfroma

file.FILENAMEissettothenameofthecurrentfile,andFNRissettozero.

TheBEGINFILEruleprovidesyoutheopportunitytoaccomplishtwotasksthatwould

otherwisebedifficultorimpossibletoperform:

Youcantestifthefileisreadable.Normally,itisafatalerrorifafilenamedonthe

commandlinecannotbeopenedforreading.However,youcanbypassthefatalerror

andmoveontothenextfileonthecommandline.

YoudothisbycheckingiftheERRNOvariableisnottheemptystring;ifso,thengawk

wasnotabletoopenthefile.Inthiscase,yourprogramcanexecutethenextfile

statement(seeThenextfileStatement).Thiscausesgawktoskipthefileentirely.

Otherwise,gawkexitswiththeusualfatalerror.

Ifyouhavewrittenextensionsthatmodifytherecordhandling(byinsertingan“input

parser”;seeCustomizedinputparsers),youcaninvokethematthispoint,beforegawk

hasstartedprocessingthefile.(Thisisaveryadvancedfeature,currentlyusedonlyby

thegawkextlibproject.)

TheENDFILEruleiscalledwhengawkhasfinishedprocessingthelastrecordinaninput

file.Forthelastinputfile,itwillbecalledbeforeanyENDrules.TheENDFILEruleis

executedevenforemptyinputfiles.

Normally,whenanerroroccurswhenreadinginputinthenormalinput-processingloop,

theerrorisfatal.However,ifanENDFILEruleispresent,theerrorbecomesnon-fatal,and



insteadERRNOisset.ThismakesitpossibletocatchandprocessI/Oerrorsatthelevelof

theawkprogram.

Thenextstatement(seeThenextStatement)isnotallowedinsideeitheraBEGINFILEor

anENDFILErule.ThenextfilestatementisallowedonlyinsideaBEGINFILErule,not

insideanENDFILErule.

Thegetlinestatement(seeExplicitInputwithgetline)isrestrictedinsidebothBEGINFILE

andENDFILE:onlyredirectedformsofgetlineareallowed.

BEGINFILEandENDFILEaregawkextensions.Inmostotherawkimplementations,orif

gawkisincompatibilitymode(seeCommand-LineOptions),theyarenotspecial.



TheEmptyPattern

Anempty(i.e.,nonexistent)patternisconsideredtomatcheveryinputrecord.For

example,theprogram:

awk'{print$1}'mail-list



printsthefirstfieldofeveryrecord.



UsingShellVariablesinPrograms

awkprogramsareoftenusedascomponentsinlargerprogramswritteninshell.For

example,itisverycommontouseashellvariabletoholdapatternthattheawkprogram



searchesfor.Therearetwowaystogetthevalueoftheshellvariableintothebodyofthe

awkprogram.

Acommonmethodistouseshellquotingtosubstitutethevariable’svalueintothe

programinsidethescript.Forexample,considerthefollowingprogram:

printf"Entersearchpattern:"

readpattern

awk"/$pattern/"'{nmatches++}

END{printnmatches,"found"}'/path/to/data



Theawkprogramconsistsoftwopiecesofquotedtextthatareconcatenatedtogetherto

formtheprogram.Thefirstpartisdouble-quoted,whichallowssubstitutionofthe

patternshellvariableinsidethequotes.Thesecondpartissingle-quoted.

Variablesubstitutionviaquotingworks,butcanpotentiallybemessy.Itrequiresagood

understandingoftheshell’squotingrules(seeShellQuotingIssues),andit’soften

difficulttocorrectlymatchupthequoteswhenreadingtheprogram.

Abettermethodistouseawk’svariableassignmentfeature(seeAssigningvariablesonthe

commandline)toassigntheshellvariable’svaluetoanawkvariable.Thenusedynamic

regexpstomatchthepattern(seeUsingDynamicRegexps).Thefollowingshowshowto

redothepreviousexampleusingthistechnique:

printf"Entersearchpattern:"

readpattern

awk-vpat="$pattern"'$0~pat{nmatches++}

END{printnmatches,"found"}'/path/to/data



Now,theawkprogramisjustonesingle-quotedstring.Theassignment‘-v

pat="$pattern"’stillrequiresdoublequotes,incasethereiswhitespaceinthevalueof

$pattern.Theawkvariablepatcouldbenamedpatterntoo,butthatwouldbemore

confusing.Usingavariablealsoprovidesmoreflexibility,asthevariablecanbeused

anywhereinsidetheprogram—forprinting,asanarraysubscript,orforanyotheruse—

withoutrequiringthequotingtricksateverypointintheprogram.



Actions

Anawkprogramorscriptconsistsofaseriesofrulesandfunctiondefinitionsinterspersed.

(Functionsaredescribedlater.SeeUser-DefinedFunctions.)Arulecontainsapatternand

anaction,eitherofwhich(butnotboth)maybeomitted.Thepurposeoftheactionisto

tellawkwhattodoonceamatchforthepatternisfound.Thus,inoutline,anawkprogram

generallylookslikethis:

[pattern]{action}

pattern[{action}]



functionname(args){…}





Anactionconsistsofoneormoreawkstatements,enclosedinbraces(‘{…}’).Each

statementspecifiesonethingtodo.Thestatementsareseparatedbynewlinesor

semicolons.Thebracesaroundanactionmustbeusedeveniftheactioncontainsonlyone

statement,orifitcontainsnostatementsatall.However,ifyouomittheactionentirely,

omitthebracesaswell.Anomittedactionisequivalentto‘{print$0}’:

/foo/{}matchfoo,donothing---emptyaction

/foo/matchfoo,printtherecord---omittedaction



Thefollowingtypesofstatementsaresupportedinawk:

Expressions

Callfunctionsorassignvaluestovariables(seeChapter6).Executingthiskindof

statementsimplycomputesthevalueoftheexpression.Thisisusefulwhenthe

expressionhassideeffects(seeAssignmentExpressions).

Controlstatements

Specifythecontrolflowofawkprograms.TheawklanguagegivesyouC-likeconstructs

(if,for,while,anddo)aswellasafewspecialones(seeControlStatementsin

Actions).

Compoundstatements

Encloseoneormorestatementsinbraces.Acompoundstatementisusedinordertoput

severalstatementstogetherinthebodyofanif,while,do,orforstatement.

Inputstatements

Usethegetlinecommand(seeExplicitInputwithgetline).Alsosuppliedinawkare

thenextstatement(seeThenextStatement)andthenextfilestatement(seeThe

nextfileStatement).

Outputstatements

Suchasprintandprintf.SeeChapter5.

Deletionstatements

Fordeletingarrayelements.SeeThedeleteStatement.



ControlStatementsinActions

Controlstatements,suchasif,while,andsoon,controltheflowofexecutioninawk

programs.Mostofawk’scontrolstatementsarepatternedaftersimilarstatementsinC.

Allthecontrolstatementsstartwithspecialkeywords,suchasifandwhile,todistinguish

themfromsimpleexpressions.Manycontrolstatementscontainotherstatements.For

example,theifstatementcontainsanotherstatementthatmayormaynotbeexecuted.

Thecontainedstatementiscalledthebody.Toincludemorethanonestatementinthe

body,groupthemintoasinglecompoundstatementwithbraces,separatingthemwith

newlinesorsemicolons.



Theif-elseStatement

Theif-elsestatementisawk’sdecision-makingstatement.Itlookslikethis:

if(condition)then-body[elseelse-body]



Theconditionisanexpressionthatcontrolswhattherestofthestatementdoes.Ifthe

conditionistrue,then-bodyisexecuted;otherwise,else-bodyisexecuted.Theelse

partofthestatementisoptional.Theconditionisconsideredfalseifitsvalueiszeroorthe

nullstring;otherwise,theconditionistrue.Refertothefollowing:

if(x%2==0)

print"xiseven"

else

print"xisodd"



Inthisexample,iftheexpression‘x%2==0’istrue(i.e.,ifthevalueofxisevenly

divisiblebytwo),thenthefirstprintstatementisexecuted;otherwise,thesecondprint

statementisexecuted.Iftheelsekeywordappearsonthesamelineasthen-bodyand

then-bodyisnotacompoundstatement(i.e.,notsurroundedbybraces),thenasemicolon

mustseparatethen-bodyfromtheelse.Toillustratethis,thepreviousexamplecanbe

rewrittenas:

if(x%2==0)print"xiseven";else

print"xisodd"



Ifthe‘;’isleftout,awkcan’tinterpretthestatementanditproducesasyntaxerror.Don’t

actuallywriteprogramsthisway,becauseahumanreadermightfailtoseetheelseifitis

notthefirstthingonitsline.



ThewhileStatement

Inprogramming,aloopisapartofaprogramthatcanbeexecutedtwoormoretimesin

succession.Thewhilestatementisthesimplestloopingstatementinawk.Itrepeatedly

executesastatementaslongasaconditionistrue.Forexample:

while(condition)

body



bodyisastatementcalledthebodyoftheloop,andconditionisanexpressionthat

controlshowlongtheloopkeepsrunning.Thefirstthingthewhilestatementdoesistest

thecondition.Iftheconditionistrue,itexecutesthestatementbody.Afterbodyhas

beenexecuted,conditionistestedagain,andifitisstilltrue,bodyexecutesagain.This

processrepeatsuntiltheconditionisnolongertrue.Iftheconditionisinitiallyfalse,the



bodyoftheloopneverexecutesandawkcontinueswiththestatementfollowingtheloop.

Thisexampleprintsthefirstthreefieldsofeachrecord,oneperline:

awk'

{

i=1

while(i<=3){

print$i

i++

}

}'inventory-shipped



Thebodyofthisloopisacompoundstatementenclosedinbraces,containingtwo

statements.Theloopworksinthefollowingmanner:first,thevalueofiissettoone.

Then,thewhilestatementtestswhetheriislessthanorequaltothree.Thisistruewheni

equalsone,sotheithfieldisprinted.Thenthe‘i++’incrementsthevalueofiandthe

looprepeats.Theloopterminateswhenireachesfour.

Anewlineisnotrequiredbetweentheconditionandthebody;however,usingonemakes

theprogramclearerunlessthebodyisacompoundstatementorelseisverysimple.The

newlineaftertheopenbracethatbeginsthecompoundstatementisnotrequiredeither,but

theprogramishardertoreadwithoutit.



Thedo-whileStatement

Thedoloopisavariationofthewhileloopingstatement.Thedoloopexecutesthebody

onceandthenrepeatsthebodyaslongastheconditionistrue.Itlookslikethis:

do

body

while(condition)



Eveniftheconditionisfalseatthestart,thebodyexecutesatleastonce(andonlyonce,

unlessexecutingbodymakesconditiontrue).Contrastthiswiththecorrespondingwhile

statement:

while(condition)

body



Thisstatementdoesnotexecutethebodyevenonceiftheconditionisfalsetobegin

with.Thefollowingisanexampleofadostatement:

{

i=1

do{

print$0

i++

}while(i<=10)

}



Thisprogramprintseachinputrecord10times.However,itisn’taveryrealisticexample,

becauseinthiscaseanordinarywhilewoulddojustaswell.Thissituationreflectsactual

experience;onlyoccasionallyistherearealuseforadostatement.



TheforStatement

Theforstatementmakesitmoreconvenienttocountiterationsofaloop.Thegeneral

formoftheforstatementlookslikethis:

for(initialization;condition;increment)

body



Theinitialization,condition,andincrementpartsarearbitraryawkexpressions,and



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Patterns, Actions, and Variables

Tải bản đầy đủ ngay(0 tr)

×