How to get input from the terminal in Perl - Stack Overflow

文章推薦指數: 80 %
投票人數:10人

I'm taking questions from the terminal and sending reply with dialog, but my program takes only the first input and repeats. For example, when I ... 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 HowtogetinputfromtheterminalinPerl AskQuestion Asked 5years,8monthsago Modified 1year,3monthsago Viewed 2ktimes 5 New!Savequestionsoranswersandorganizeyourfavoritecontent.Learnmore. IamcreatingasimplechatterbotprogramlikeELIZA. I'mtakingquestionsfromtheterminalandsendingreplywithdialog,butmyprogramtakesonlythefirstinputandrepeats. Forexample,whenIrunmyscripttheoutputmaybesomethinglikethis: [Eliza]:Hi,I'mapsychotherapist.Whatisyourname? userInput:hellomynameisadam. [Eliza]:helloadam,howareyou? [Eliza]:yournameisadam [Eliza]:yournameisadam [Eliza]:yournameisadam [Eliza]:yournameisadam [Eliza]:yournameisadam Anditrepeatsendlessly. Idon'tknowwhereIamdoingwrong.HowcanIgetmyprogramtoreadthenextlinefromthekeyboard? subhello{ print"[Eliza]:Hi,I'mapsychotherapist.Whatisyourname?\n"; } subgetPatientName{ my($reply)=@_; my@responses=("mynameis","i'm","iam","myname's"); foreachmy$response(@responses){ if(lc($reply)=~/$response/){ return"$'"; } } returnlc($reply); } submakeQuestion{ my($patient)=@_; my%reflections=( "am"=>"are", "was"=>"were", "i"=>"you", "i'd"=>"youwould", "i've"=>"youhave", "i'll"=>"youwill", "my"=>"your", "are"=>"am", "you've"=>"Ihave", "you'll"=>"Iwill", "your"=>"my", "yours"=>"mine", "you"=>"me", "me"=>"you" ); if($count==0){ $patientName=getPatientName($patient); $count+=1; print"Hello$patientName,Howareyou?\n"; } my@toBes=keys%reflections; foreachmy$toBe(@toBes){ if($patient=~/$toBe/){ $patient=~s/$toBe/$reflections{$toBe}/i; print"$patient?\n"; } } } subeliza{ hello(); my$answer=; while($answer){ chomp$answer; #remove.!; $answer=~s/[.!,;]//; makeQuestion($answer); } } eliza(); perl Share Follow editedJul6,2021at14:37 PeterMortensen 30.6k2121goldbadges102102silverbadges124124bronzebadges askedJan31,2017at5:58 KeroKero 1,88444goldbadges3030silverbadges4949bronzebadges 2 4 Itseemsthatallyouneediswhile(my$answer=).Whatyouhave"loopsover"$answer...whichisalwaystrue(soitkeepsgoing),andwhichneveragainreadsnewinput(soitkeepsprintingthesame). – zdim Jan31,2017at6:03 @zdim:Ithink"loopingover"generallyreferstoalist,likeaforstatement. – Borodin Jan31,2017at6:43 Addacomment  |  2Answers 2 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 6 Yourwhileloopneverreadsinput.The$answergotSTDINbeforetheloopandpresumablyhasastring,thatevaluatestrueinthewhilecondition.Theregexintheloopcannotchangethat. Thusnotonlyisnonewinputassignedto$answer,butafterthefirstiterationnothingatallchangesintheloop.Soitkeepsrunningforever,printingthequestionbasedonthesame$answer. Youneed while(my$answer=){ chomp$answer; #... } instead. Everytimetheconditionofwhile(...)isevaluatedthenewinputisreadviaandisassignedto$answer.Theneachnewquestionusesthenew$answer.Notehowavariablemaybedeclaredinsidethewhileconditionsotoexistonlyinsidetheloopbody(andintheconditionafteritsdeclaration).Thisisanicewaytokeepitsscoperestrictedtowhereitisneeded,insidetheloop. Thefilehandleread<...>returnsundefwhenitgetsEOF(oronerror)andtheloopterminates.SeeI/OOperatorsinperlop.AuserattheterminalcannormallyachievethisbyCtrl-d. Share Follow editedJun6,2020at21:27 answeredJan31,2017at6:12 zdimzdim 60k44goldbadges5050silverbadges7777bronzebadges Addacomment  |  -3 AtypicalPerlscriptthatusescommand-lineargumentswill testforthenumberofcommandlineargumentstheusersupplied attempttousethem. Seethebelowcode. #!/usr/bin/perl-w #(1)quitunlesswehavethecorrectnumberofcommand-linearguments $num_args=$#ARGV+1; if($num_args!=2){ print"\nUsage:name.plfirst_namelast_name\n"; exit; } #(2)wegottwocommand-linearguments,soassumetheyarethe #firstnameandlastname $first_name=$ARGV[0]; $last_name=$ARGV[1]; print"Hello,$first_name$last_name\n"; Share Follow editedJul6,2021at14:39 PeterMortensen 30.6k2121goldbadges102102silverbadges124124bronzebadges answeredJan31,2017at12:44 shekharpandeshekharpande 1,15211goldbadge1111silverbadges2121bronzebadges 1 1 unfortunatelyyouarenotansweringthequestion.OPdoesnotaskaboutcommandlinearguement,butasksaboutinputfromstdin,cin.Notparametersgiventoexecutetheprograms,likeyouareanswering.Sorrytodown-vote,youranswerisnotfalseinitself,butonstackoverflow,butwehavetofocusonansweringthegoodquestion.Hereyouarenotansweringthequestion. – StephaneRolland Jun6,2020at14:16 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 Related 300 HowcanIstartaninteractiveconsoleforPerl? 180 HowdoIgetthefullpathtoaPerlscriptthatisexecuting? 317 HowdoIbreakoutofaloopinPerl? 204 Whatisthedifferencebetween'my'and'our'inPerl? 236 HowdoIusebooleanvariablesinPerl? 197 HowdoIcomparetwostringsinPerl? 749 HowtofixalocalesettingwarningfromPerl 275 HowcanIcheckifaPerlarraycontainsaparticularvalue? 2 patternmatchingandregularexpressioninperl? HotNetworkQuestions Meaningof"Allthemcreepsinthatstoretostealfrom,Arnie'sgottopickoutaladybulltoclip!" Whydoweneedmixedstatesinquantummechanics? Shouldmy240velectricstovebegroundedtotheneutrallikethis? HowcanIconnectTikZnodeswithmultiple-cornerlines? HowcanIkeeptheexistingguideswhentheunderlyingfileisupdatedinPhotoshop? WhyareringsnotafavoriteoptioninITnetworks? Doesaparallelairgapincreaseordecreasemaximumenergystoredinmagneticfieldofaninductor? Isablackmoonpossible? Howtoobtainaminor'spassportwithanabsentparent Isthereamore"physicallymature"waytothinkabouttherighthandrulewithelectromagnetism? Whydocourtopinionslistmultiplelayersofcitations? WhatexactlywerethoselargeorangechipsontheHayesMicromodemIIinterfacecard? IsGoogleStreetViewcoverageinGermanyexpectedtoincrease? WhydoesMOS6502requireanexternalclockifithasaninternaloscillator? Graphingfloorandceilingfunctions Whyaretheredollaramountslistednearthecopyrightinformationforjournalarticles? DoRSAsignaturesreallyneedpadding? Ifform8606isnotrequiredtosubmitforjustRothIRAcontributions?HowdoesIRSenforcethelimit? Whataredisadvantagesofaerodropbars? Isthephrasestill"cuantosañostiene"wheretheageisobviouslylessthanoneyear? AlphabetChecksum Whywouldatechnologicallyadvancedsocietyusehumancontrollerstodirectspaceshiptraffic? Selectrankofsinglerow Element-wisecomparisonsofsortedsubsetsofrandomnumbersyieldnonrandomresults morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-perl Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?