Tải bản đầy đủ - 0 (trang)
Chapter 7. If Only, Unconditionally, Forever

Chapter 7. If Only, Unconditionally, Forever

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

Sofar,wehaveseenscriptexamplesthatarelinearin

structure;thatis,simplestatementsthatareexecutedin

sequence,oneaftertheother.Controlstructures,suchas

branchingandloopingstatements,allowtheflowofthe

program'scontroltochangedependingonsomeconditional

expression.

Thedecision-makingconstructs(if,if/else,if/elsif/else,unless,

etc.)containacontrolexpressionthatdetermineswhethera

blockofstatementswillbeexecuted.

Theloopingconstructs(while,until,for,foreach)allowthe

programtorepetitivelyexecuteastatementblockuntilsome

conditionissatisfied.

Acompoundstatement,orblock,consistsofagroupof

statementssurroundedbycurlybraces.Theblockis

syntacticallyequivalenttoasinglestatementandusually

followsanif,else,while,orforconstruct.ButunlikeC,where

curlybracesarenotalwaysrequired,Perlrequiresthemeven

withonestatementwhenthatstatementcomesaftertheif,

else,while,etc.Theconditionalmodifiers,discussedinChapter

8,"RegularExpressions—PatternMatching,"canbeusedwhen

aconditionisevaluatedwithinasinglestatement.



7.1.1.DecisionMaking—ConditionalConstructs

ifandunlessStatements



Theifandunlessconstructsarefollowedbyanexpression

surroundedbyparenthesesandfollowedbyablockofonemore

statements.Theblockisalwaysenclosedincurlybraces.

Anifstatementisaconditionalstatement.Itallowsyoutotest

anexpressionand,basedontheresultsofthetest,makea

decision.Theexpressionisenclosedinparentheses,andPerl

evaluatestheexpressioninastringcontext.Ifthestringis

non-null,theexpressionistrue;ifitisnull,theexpressionis

false.Iftheexpressionisanumericvalue,itwillbeconverted

toastringandtested.Iftheexpressionisevaluatedtobetrue

(non-null),thenextstatementblockisexecuted;ifthe

conditionisfalse(null),Perlwillignoretheblockassociated

withtheexpressionandgoontothenextexecutablestatement

withinthescript.

Theunlessstatementisconstructedexactlythesameastheif

statement;theresultsofthetestaresimplyreversed.Ifthe

expressionisevaluatedtobefalse,thenextstatementblockis

executed;iftheexpressionisevaluatedtobetrue,Perlwill

ignoretheblockofstatementscontrolledbytheexpression.



TheifConstruct

Theifstatementconsistsofthekeywordif,followedbya

conditionalexpression,followedbyablockofoneormore

statementsenclosedincurlybraces.Eachstatementwithinthe

blockisterminatedwithasemicolon(;).Theblockof

statementscollectivelyisoftencalledacompoundstatement.

Makesurewhenyouaretestingstringsthatyouusethestring

operatorsshowninTable6.7andthatiftestingnumbers,you

usethenumericoperatorsalsoshowninTable6.6.Perl

convertsstringsandnumberstoconformtowhattheoperator

expects,sobecareful.Atestsuchas"yes"=="no"is

incorrect.Itshouldbe"yes"eq"no".



Format

if(Expression){Block}

if(Expression){Block}else{Block}

if(Expression){Block}elsif(Expression)

{Block}...else{Block}



Example7.1.

(TheScript)

1print"Howoldareyou?";

2chomp($age=);

3if($age>=21){#Iftrue,entertheblock

4print"Let'sparty!\n";

}

5print"Yousaidyouwere$age.\n";

(Output)

1Howoldareyou?32

4Let'sparty!

5Yousaidyouwere32.

-------------Runtheprogramagain------------(Output)

1Howoldareyou?10

5Yousaidyouwere10.



Explanation

1. Theuserisaskedforhisage.

2. Thescalar$ageisassignedavalue.

3. Thescalar$ageistested.Ifitsvalueisgreater

thanorequalto21(i.e.,theexpressionevalutaes

totrue),thentheblockisenteredandline4is

executed.

4. Iftheuserisolderthan21,thislineisprinted.The

curlybracesenclosingtheblockaftertheifarenot

optional.Theyarerequired!

5. Programcontrolcontinuesherewhetherornotthe

ifblockwasexecuted.



Theif/elseConstruct

Anotherformoftheifstatementistheif/elseconstruct.This

constructallowsforatwo-waydecision.Ifthefirstconditional

expressionfollowingtheifkeywordistrue,theblockof

statementsfollowingtheifareexecuted.Otherwise,ifthe

conditionalexpressionfollowingtheifkeywordisfalse,control

branchestotheelse,andtheblockofstatementsfollowingthe

elseareexecuted.Theelsestatementisneveranindependent

statement.Itmustfollowanifstatement.Whentheif

statementsarenestedwithinotherifstatements,theelse

statementisassociatedwiththeclosestpreviousifstatement.



Format

if(Expression)

{Block}

else

{Block}



Example7.2.



(TheScript)

1print"Whatversionoftheoperatingsystemareyouusing?

2chomp($os=);

3if($os>2.2){print"Mostofthebugshavebeenworked

out!\n";}

4else{print"Expectsomeproblems.\n";}

(Output)

1Whatversionoftheoperatingsystemareyouusing?2.4

3Mostofthebugshavebeenworkedout!

(Output)

1Whatversionoftheoperatingsystemareyouusing?2.0

4Expectsomeproblems.



Explanation

1. Theuserisaskedforinput.

2. Thenewlineisremoved.

3. Ifthevalueof$osisgreaterthan2.2,theblock

enclosedincurlybracesisexecuted.Ifnot,

programcontrolgoestotheelseonline4.

4. If$osisnotgreaterthan2.2,thisblockis

executed.



Theif/elsif/elseConstruct

Yetanotherformoftheifstatementistheif/else/elsif

construct.Thisconstructprovidesamultiwaydecision

structure.Ifthefirstconditionalexpressionfollowingtheif

keywordistrue,theblockofstatementsfollowingtheifis

executed.Otherwise,thefirstelsifstatementistested.Ifthe

conditionalexpressionfollowingthefirstelsifisfalse,thenext

elsifistested,etc.Ifalloftheconditionalexpressionsfollowing

theelsifsarefalse,theblockaftertheelseisexecuted;thisis

thedefaultaction.



Format

if(Expression1)

{Block}

elsif(Expression2)

{Block}

elsif(Expression3)

{Block}

else

{Block}



Example7.3.



(TheScript)

1$hour=(localtime)[2];

2if($hour>=0&&$hour<12){print"Good–morning!\n";}

3elsif($hour==12){print"Lunchtime.\n";}

4elsif($hour>12&&$hour<17){print"Siestatime.\n";}

5else{print"Goodnight.Sweetdreams.\n";}

(Output)

4Siestatime



Explanation

1. Thescalar$hourissettothecurrenthour.The

localtimebuilt-infunctionreturnsthehour,the

thirdelementofthearrayoftimevalues.

2. Theifstatementtestswhetherthevalueof$houris

greaterthanorequalto0andlessthan12.The

resultoftheevaluationistrue,sotheblock

followingthecontrolexpressionisexecuted(i.e.,

theprintstatementisexecuted).

3. Ifthefirstiftestisfalse,thisexpressionistested.

Ifthevalueof$hourisequalto12,theprint

statementisexecuted.

4. Ifthepreviouselsiftestfailed,andthiselsif

expressionevaluatestotrue,theprintstatement

willbeexecuted.

5. Ifnoneoftheabovestatementsistrue,theelse

statement,thedefaultaction,isexecuted.



TheunlessConstruct

Theunlessstatementissimilartotheifstatement,exceptthat

thecontrolexpressionaftertheunlessistestedforthereverse

condition;thatis,iftheconditionalexpressionfollowingthe

unlessisfalse,thestatementblockisexecuted.

Theunless/elseandunless/elsifbehaveinthesamewayasthe

if/elseandif/elsifstatementswiththesamereversedtestas

previouslystated.



Format

unless(Expression){Block}

unless(Expression){Block}else{Block}

unless(Expression){Block}elsif(Expression)

{Block}...else{Block}



Example7.4.

(TheScript)

1print"Howoldareyou?";

2chomp($age=);

3unless($age<=21){#Iffalse,entertheblock

4print"Let'sparty!\n";

}

5print"Yousaidyouwere$age.\n";

(Output)

1Howoldareyou?32

4Let'sparty!

5Yousaidyouwere32.

-------------Runtheprogramagain------------(Output)

1Howoldareyou?10

5Yousaidyouwere10.



Explanation

1. ThisexampleisexactlylikeExample7.1exceptthe

logicintheconditionisreversed.Wewilltestfor

falseratherthantrue.Theuserisaskedforhis

age.

2. Thescalar$ageisassignedavalue.

3. Thescalar$ageistested.Unlessitsvalueisless

thanorequalto21(i.e.,theexpressionevaluates

tofalse),thentheblockisenteredandline4is

executed.

4. Iftheuserisnot21orolder,thislineisprinted.

Thecurlybracesenclosingtheblockaftertheifare

notoptional.Theyarerequired!

5. Programcontrolcontinuesherewhetherornotthe

ifblockwasexecuted.





Example7.5.

CodeView:

(TheScript)

#!/bin/perl

#Scriptname:excluder

1while(<>){

2($name,$phone)=split(/:/);

3unless($nameeq"barbara"){

$record="$name\t$phone";

4print"$record";



}

}

5print"\n$namehasmovedfromthisdistrict.\n";

(Output)

$excludernames

igorchevsky408-123-4533

pacogutierrez510-453-2776

ephramhardy916-235-4455

jamesikeda415-449-0066

barbarakerz207-398-6755

josesantiago408-876-5899

tommysavage408-876-1725

lizzystachelin415-555-1234

barbarahasmovedfromthisdistrict.

























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

Chapter 7. If Only, Unconditionally, Forever

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

×