return is the equivalent of return. next is the equivalent of continue. last is the equivalent of break. 'if' statements are followed by blocks.
Home
Public
Questions
Tags
Users
Companies
Collectives
ExploreCollectives
Teams
StackOverflowforTeams
–Startcollaboratingandsharingorganizationalknowledge.
CreateafreeTeam
WhyTeams?
Teams
CreatefreeTeam
StackOverflowforTeamsismovingtoitsowndomain!Whenthemigrationiscomplete,youwillaccessyourTeamsatstackoverflowteams.com,andtheywillnolongerappearintheleftsidebaronstackoverflow.com.
Checkyouremailforupdates.
Collectives™onStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
LearnmoreaboutCollectives
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
LearnmoreaboutTeams
WhatarethePerlequivalentsofreturnandcontinuekeywordsinC?
AskQuestion
Asked
12years,2monthsago
Modified
12years,2monthsago
Viewed
22ktimes
26
New!Savequestionsoranswersandorganizeyourfavoritecontent.Learnmore.
IamgettingthiserrorwhenIusethiscode
subsearch{
my($a,@a_list)=@_;
foreach(@a_list){
if($_==$a)returnTRUE;
#continue;
}
returnFALSE;
}
syntaxerroratcode.plline26,near")return"
WhatistherightwaytoreturnTRUE?
Also,whatistherightwaytocontinue?
IknowIshouldbethinkingmoreinPerltermsthantryingtoconvertCcodetoPerlthisway.
perl
Share
Improvethisquestion
Follow
editedAug26,2010at15:40
Lazer
askedAug26,2010at14:14
LazerLazer
87.5k112112goldbadges276276silverbadges357357bronzebadges
1
3
Yoursearchfunctioncanbecollapsedintoacalltoany:useList::MoreUtils'any';my$matched=any{$_eq$a}@a_list;
– Ether
Aug26,2010at16:37
Addacomment
|
3Answers
3
Sortedby:
Resettodefault
Highestscore(default)
Trending(recentvotescountmore)
Datemodified(newestfirst)
Datecreated(oldestfirst)
58
Equivalentsofreturn,continue,break
returnistheequivalentofreturn.
nextistheequivalentofcontinue.
lastistheequivalentofbreak.
'if'statementsarefollowedbyblocks
Yourproblemisthatanifstatementisalwaysfollowedbyablockinsidebraces.
if($_==$a){returnTRUE;}
elsif(...){...}
else{...}
Forallitsometimesseemsabitverbose,IagreewithysththatthisissomethingthatPerlgotright.Foraninterestingalternativetake,seetheGoprogramminglanguage,whichtreatstheparenthesesasunnecessaryandmandatesthebraces.
'if'canbeusedasaqualifier
Oryoucanusetheifasastatementmodifier:
returnTRUEif$_==$a;
Notethatinthiscase,youdon'thavetouseparenthesesaroundtheconditionalexpression,thoughthere'dbenoharminaddingthem.
Using'unless'
Youcanalsouseunlessinsteadofiftoinvertthecondition:
returnTRUEunless$_!=$a;
(And,asPhillipPotterpointedout,mixingunlesswithanegatedconditionmakescomprehensionharder;theexampleisdirectlydoingthesameasthequestion,butisbetterwrittenasanifwithequality.)
Using'next'and'last'
Youcanusenextandlastsimilarly:
subsearch{
my($a,@a_list)=@_;
foreach(@a_list){
returnTRUEif$_==$a;
lastif$_>$a;
nextif$ptom!=LAST_QUARTER;
...
}
returnFALSE;
}
Notethefixupintheforeachloop.(Questionamendedtoincludethefixup.)Makesureyoualwayshave'usestrict;'and'usewarnings;'atthetopofyourscript.Expertsalwaysusethemtomakesuretheyhaven'tmademistakes.Beginnersshouldusethemforexactlythesamereason.
TRUEandFALSE
Also,aspointedoutfirstinotheranswers,Perldoesnothavepre-definedconstantsTRUEandFALSE,anymorethanCorC++do(C++hasabuilt-intrueandfalse;C99hastrueandfalseconditionallyavailableifyou#include).YoucanprovidethedefinitionsforPerlas:
useconstantTRUE=>1;
useconstantFALSE=>0;
Bewary,though.Somethingswillbe'true'evenwhennotequaltoTRUE;otherthingswillbe'false'evenwhennotequaltoFALSE.
Discussionaboutuseof'$a'and'$b'
Thecommentscontainadiscussionaboutnotusing$aand$basvariables.Insequence,therelevantcommentswere:
Pleaseavoidusing$aunlessit'sinasortblock.–Zaid
@Zaid:Goodpointthat$aand$barespecialinthecontextofasortblock.I'mnotsurewhetherthereareedictsthattheyshouldneverbeusedotherwise-itwouldbeatrocioustousethemwhenthereisalsoasortblocklurkingaround,butintheabsenceofsortblocks,Idon'tseeanyreasontotreat$aanddifferentthan$z.–JonathanLeffler
$aand$bareglobals,andassuchbehavedifferentthanlexicals.–phaylon
@phaylon:well,strictlytheyare'packageglobals'(seePerlsort).Yes,whenyouaresorting,theyaredifferentfromlexicals(my)variables.Whenyouaren'tdoingsorting,thentheycanbetreatedaslexicalsifyoudeclarethemexplicitly.–JonathanLeffler
@JonathanLeffler,theyarealsoexemptfromusestrictqw(vars);soyoumightnotnoticethatyouaretramplingonthemfromanotherscope.–Ven'Tatsu
Pointingouttheobvious:Ionlyused$abecausethequestiondid-andratherthaninundatetheoriginalposterwithlotsofdetails,Ikeptmostlytothemainpoints.Forexample,thediscussionoflastandnextdoesnotmentionlooplabels.
Thatsaid,theadvice"avoidusing$aand$basvariables"issound;theyarespecialnamesforthereasonspointedout,andusingthemleavesopenthepossibilityofmistakesthatmayormaynotbebedetectable.
Share
Improvethisanswer
Follow
editedMay23,2017at11:33
CommunityBot
111silverbadge
answeredAug26,2010at14:18
JonathanLefflerJonathanLeffler
709k135135goldbadges878878silverbadges12391239bronzebadges
10
4
...butdon'teveruseunlesswithanegativeconditionsuchasonewhichuses!or!=.It'sthecodeequivalentofadoublenegative,anditjustconfusespeople.
– PhilipPotter
Aug26,2010at14:25
4
Pleaseavoidusing$aunlessit'sinasortblock.
– Zaid
Aug26,2010at14:27
2
@Zaid:Goodpointthat$aand$barespecialinthecontextofasortblock.I'mnotsurewhetherthereareedictsthattheyshouldneverbeusedotherwise-itwouldbeatrocioustousethemwhenthereisalsoasortblocklurkingaround,butintheabsenceofsortblocks,Idon'tseeanyreasontotreat$aanddifferentthan$z.
– JonathanLeffler
Aug26,2010at14:31
1
@JonathanLeffler:$aand$bareglobals,andassuchbehavedifferentthanlexicals.
– phaylon
Aug26,2010at17:10
1
@JonathanLeffler,theyarealsoexemptfromusestrictqw(vars);soyoumightnotnoticethatyouaretramplingonthemfromanotherscope.
– Ven'Tatsu
Aug26,2010at21:55
|
Show5morecomments
7
Yourquestionhasbeen(very!)comprehensivelyansweredbyJonathan,butIwantedtopointoutafewother,moreperlishwaystoreplaceyour"search"function.
usestrict;
usewarnings;
use5.010;
my@a_list=(1,2,3);
my$a=2;
#Ifyou'reusing5.10orhigher,youcanusesmartmatching.
#Notethatthisisonlyequivalentif$aisanumber.
#Thatis,"2.0"~~["1","2","3"]isfalse.
say$a~~@a_list;
#NeedtoinstallList::MoreUtils,notastandardmodule
useList::MoreUtilsqw(any);
sayany{$a==$_}@a_list;
#List::Utilisacoremodule
useList::Utilqw(first);
saydefinedfirst{$a==$_}@a_list;
#Nomodulesused,butlessefficient
saygrep{$a==$_}@a_list>0;
Formoreinfo,seethedocumentationforsmartmatching,List::MoreUtils,
List::Utilandgrep.
Share
Improvethisanswer
Follow
editedAug26,2010at15:30
answeredAug26,2010at15:23
mschamscha
6,48933goldbadges2323silverbadges4040bronzebadges
Addacomment
|
4
Perldoesnothavebuiltinconstantsfortrueandfalse.Thecanonicalvaluefortrueis1andforfalseis()(whichisanemptylistinlistcontext,andundefinscalarcontext).
Amoreidomaticwaytowriteyourcodewouldbe:
subsearch{
my$key=shift;
foreach(@_){
return1if$_==$key;
}
return();
}
Share
Improvethisanswer
Follow
editedAug26,2010at14:31
answeredAug26,2010at14:26
EricStromEricStrom
39.5k22goldbadges7878silverbadges152152bronzebadges
Addacomment
|
YourAnswer
ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers.
Draftsaved
Draftdiscarded
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingEmailandPassword
Submit
Postasaguest
Name
Email
Required,butnevershown
PostYourAnswer
Discard
Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy
Nottheansweryou'relookingfor?Browseotherquestionstaggedperloraskyourownquestion.
TheOverflowBlog
IntroducingtheOverflowOfflineproject
Hehelpedbuild.NETandVSCode—Now’sheworkingonWeb3(Ep.499)
FeaturedonMeta
The2022Community-a-thonhasbegun!
Mobileappinfrastructurebeingdecommissioned
CollectivesUpdate:RecognizedMembers,Articles,andGitLab
The[script]tagisbeingburninated
StagingGroundWorkflow:CannedComments
Linked
2
tonsof"Useofuninitializedvaluewithin%genetic_codeinsubstitutioniterator"
Related
33
Whatarethecommonworkaroundsformulti-linecommentsinPerl?
17
InPerl,howcanItestwhetherasequenceisoftheformn,n+1,n+2,...,n+k?
4
Whatdoesthe`->`syntaxmeaninPerl?
10
HowtowritethecurrenttimestampinaPerlfile?
7
WhatdoesthePerlasterisksigildo
8
WhatvaluesshouldabooleanfunctioninPerlreturn?
HotNetworkQuestions
WhyistheUSvowingtoprotectTaiwanwhentheywon'tprotectUkraine?
awk-IFcolumn$1isnotequaltothepreviouscolumn$1thenprintentirepreviousline
Freemedianalgebrasandmaximallinkedsystems
Isthereamore"physicallymature"waytothinkabouttherighthandrulewithelectromagnetism?
1v1barteringbraingame– seeanyproblems?
Whataredisadvantagesofaerodropbars?
WhyareUKprimeministersresigning,ratherthanwaitingouttheirtermandenjoyingthebenefits?
Isthet-testmiscalibratedinR?
Arelawswrittenlogicallyandrigorously?
Isthereawayasocietycouldproducetanksascheaplyascars?
DoRSAsignaturesreallyneedpadding?
Whywouldaplaneflyincircles?
WhereisthisparkinMontreal,withautumncolortreesandpond?
Synonymfor"fortunately"inacademiclanguage
Nomatchingfunctionforcallto'DS3231(constuint8_t&,constuint8_t&)
ShouldItellmyadvisormyfianceleftme?
HowdoIcreategeometry/texturesforproceduralshading?
CanyoubetterexplainthePF1efeatFastLearner(Human)?
Controlthezscaleofinstanceswithempty
Zeropaddingversuszerostuffing
EquilibriumconstantvsReactionrateconstant
Withoutwind,wouldaplanegostraightifthepilotletgoofthecontrols?
Whatwouldan"excessivelysober"dwarflooklikeiftheyneedalcoholtofunction?
ID10TCheck:6/2SouthwireSIMpullStrandedIsAcceptablefor50AMPCooktopRun
morehotquestions
Questionfeed
SubscribetoRSS
Questionfeed
TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader.
lang-perl
Yourprivacy
Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy.
Acceptallcookies
Customizesettings