Subroutines - Perl 101

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

Subroutines. Retrieving arguments to a subroutine with shift. A subroutine's arguments come in via the special @_ array. The shift without an argument ... IndexHowtogetPerlTermsDocumentationStringsNumbersArraysHashesRegexesFlowControlFilesSubroutinesPODDebuggingModulesModules:MakingyourownExternalprogramsCPANConstructsReferencesObjectsSpecialVariablesCommand-lineSwitchesAdvancedFunctionsStylePerformanceTrapsEmailHowdoI...?DeveloperToolsWebsitesPublicationsCommunityRandomTODOCodeofConduct Subroutines Retrievingargumentstoasubroutinewithshift Asubroutine'sargumentscomeinviathespecial@_array. Theshiftwithoutanargumentdefaultsto@_. subvolume{ my$height=shift; my$width=shift; my$depth=shift; return$height*$width*$depth; } Assignargumentstoasubroutinewithlistassignment Youcanalsoassignargumentsenmassewithlistassignment: subvolume{ my($height,$width,$depth)=@_; return$height*$width*$depth; } Handleargumentsdirectlybyaccessing@_ Insomecases,butwehopeveryfew,youcanaccessargumentsdirectlyinthe@_array. subvolume{ return$_[0]*$_[1]*$_[2]; } Argumentspassedcangetmodified Theargumentspassedtoasubroutinearealiasestotherealarguments. my$foo=3; printincr1($foo)."\n";#prints4 print"$foo\n";#prints3 subincr1{ return$_[0]+1; } Thiscanbegoodifyouwantittobe: subincr2{ return++$_[0]; } Subroutineshavenoargumentchecking Youcanpassanyanythingtoasubroutinethatyouwant. subsquare{ my$number=shift; return$number*$number; } my$n=square('Dogfood',14.5,'Blahblahblah'); Onlythefirstargumentisusedbythefunction.Forthatmatter,youcancallthefunctionwithanynumberofarguments,evennoarguments: my$n=square(); andPerlwon'tcomplain. ThemoduleParams::Validatesolvesmanyofthesevalidationproblems. Perlhas"prototypes".Ignorethem. Somewherealongtheway,prototypesgotadded,soyoucandothingslikethis: subsquare($){ ... } my$n=square(1,2,3);#run-timeerror However,don'tusethem.Theydon'tworkonobjects,andtheyrequirethatthesubroutinesbedeclaredbeforethey'recalled.They'reaniceidea,butjustnotpractical. MakethingshappenatcompiletimewiththeBEGINblock BEGINisaspecialtypeofcodeblock.ItallowsprogrammerstoexecutecodeduringPerl'scompilephase,allowingforinitializationsandotherthingstohappen. PerlusesBEGINanytimeyouuseamodule;thefollowingtwostatementsareequivalent: useWWW::Mechanize; BEGIN{ requireWWW::Mechanize; importWWW::Mechanize; } Passinarraysandhashesasreferences Rememberthattheparameterspassedintoasubroutinearepassedasonebigarray.Ifyoudosomethinglikethefollowing: my@stooges=qw(MoeLarryCurly); my@sandwiches=qw(tunaham-n-cheesePBJ); lunch(@stooges,@sandwiches); Thenwhat'spassedintolunchisthelist ("Moe","Larry","Curly","tuna","ham-n-cheese","PBJ"); Insidelunch,howcanyoutellwherethestoogesendandthesandwichesbegin?Youcan't.Ifyoutrythis: sublunch{ my(@stooges,@sandwiches)=@_; thenallsixelementsgointo@stoogesand@sandwichesgetsnothing. Theansweristousereferences,asin: lunch(\@stooges,\@sandwiches); sublunch{ my$stoogeref=shift; my$sandwichref=shift; my@stooges=@{$stoogeref}; my@sandwichref=@{$sandwichref}; ... } Wanttocontribute? SubmitaPRtogithub.com/petdance/perl101 ThisworkislicensedunderaCreativeCommonsAttribution-ShareAlike4.0InternationalLicense.



請為這篇文章評分?