Perl Command Line Arguments | argv - Javatpoint
文章推薦指數: 80 %
Command line arguments are sent to a Perl program in the same way as in any other language. The @ARGV array holds the command line argument. There is no need to ... ⇧SCROLLTOTOP Home Perl C C++ C# Java MySQL HTML CSS Bootstrap JavaScript jQuery XML Quiz Projects InterviewQ Comment Forum Training PerlTutorial PerlTutorial PerlIntroduction PerlInstallation PerlFirstExample Perlprint()&say() PerlSTDIN PerlVersion PerlDataTypes PerlVariables PerlScalars PerlOperators PerlOperatorTypes PerlControlStatement Perlif-else Perlswitch Perlgoto PerlComments PerllastStatement PerlnextStatement PerlredoStatement PerlforLoop PerlwhileLoop Perldo-whileLoop PerlArrays PerlArray PerlArraywithLoops MultidimensionalArray PerlStrings PerlString PerlEscapingCharacters PerlNamespace Modules&Namespace PerlHashes PerlHashes PerlRegex PerlRegularexpressions Perlsplit()andjoin() PerlFunctions Functions&Subroutines PerlFilehandling PerlFilehandling Perlchop()vschomp() PerlDirectory PerlDirectories PerlErrorHandling PerlErrorHandling PerlAdvanced PerlDBI(Database) PerlObjectOriented PerlDateTime PerlSocketProgramming PerlCommandArgs PerlCreateExcel PerlInterview PerlInterviewQuestions next→ ←prev PerlCommandLineArguments CommandlineargumentsaresenttoaPerlprograminthesamewayasinanyotherlanguage.The@ARGVarrayholdsthecommandlineargument.Thereisnoneedtousevariablesevenifyouuse"usestrict".Bydefault,thisvariablealwaysexistsandvaluesfromthecommandlineareautomaticallyplacedinsidethisvariable.Toaccessyourscript'scommand-linearguments,youjustneedtoreadfrom@ARGVarray. Perlallowsusing@ARGVarrayasfilenamesbyusing<>.The$ARGVcontainsthenameofthecurrentfilewhenreadingfrom<>. @ARGVarrayelements [email protected]$ARGV[0],second$ARGV[1],andsoon. PerlCommandLineArgumentExample Let'sseeasimpleexampletoprintcommandlinearguments.Inthisexample,wewillprintawelcomemessagewiththeusersnameastheargumentfromthecommandline.Weneedtwocommandlineargumentsasuser'sfirstandlastname. Step1Createascriptwelcome.plinyoursystem. #!/usr/bin/perl-w #(1)checkforthenumberofcommand-lineargumentsentered $number_args=$#ARGV+1; if($number_args!=2){ print"Wrongentry.Pleaseenteryourfullname.\n"; exit; } #(2)iftwocommandlineargumentsreceived, $firstName=$ARGV[0]; $lastName=$ARGV[1]; print"Welcome$firstName$lastNameatJavaTpoint.\n"; Intheabovescript,firstitwillcheckwhethertwocommandlineargumentsareprovidedornot.Ifnot,itwillgivethewrongentryerror.Andifyes,itwillprocessthoseargumentsas$ARGV[0]and$ARGV[1]respectively. Step2Runthescriptinyourconsoleasperlwelcome.plChristianGrey Note:Beforegivingthiscommand,makesureyouareonthedirectorycontainingyourscriptwelcome.pl Thisistheoutputyouwillgetinyourconsole. Step2Runthescriptinyourconsoleasperlwelcome.plChristian Here,wearepassingonlyoneargumentfromthecommandline. Intheoutput,youcanseethewrongentrymessageforpassingoneargument. PerlCommandLineArgumentsExampleusingLoop Nowwewillrunalooptoprintthecommandlinearguments.Inthisexample,youcanenterasmuchargumentasyouwish. Step1Createascriptloop.plinyoursystem. #!/usr/bin/perl $get_args=$#ARGV+1; print"Totalcommandlineargumentsreceived:$get_args\n"; foreach$argument(0..$#ARGV){ print"$ARGV[$argument]\n"; } Step2Runthescriptinyourconsoleasperlloop.plabcdefgh Lookattheoutputabove,italsodisplaystotalargumentspassedoncommandline.Herewehavepassed8arguments. PerlGetopt::Long Thesimplecommandlineoptionsaredoneusing?soption.ComplexcommandlineoptionsaredoneusingGetopt::StdandGetopt::Long. GetoptstandsforGetOptions.Itprocessesthecontentof@ARGVbasedontheconfigurationwegivetoit.Itreturnstrueorfalsevaluebasedontheprocessing. Example: Inthisexample,wewellgettheageoftheuserfromthecommandline. usestrict; usewarnings; use5.010; useGetopt::Longqw(GetOptions); my$x; GetOptions('from=s'=>\$x)ordie"Usage:$0--fromNAME\n"; say"Accordingtoyouragewhichis$x:"; if($x>=18){ say"Youareeligibletovote"; } Wehavedeclaredavariable$xwhichwillstorevalueinsertedinto--fromfromthestandardconsole.Thefrom=sdeclarescommandlineparametercalled--fromwithastringafterit.Itismappedfurthertothevariable$x.Thebackslash(\)meanswearepassingareferencetothevariable. Thisscriptwillswitchtodiepartonlywhenwewillrunthisscriptbypassingsomethingthatlookslikeaparameternameandstartswitha(-)butisnotdeclaredinthisscript. Now,wewillrunthisprogram. Output: Lookattheoutput,afterenteringageontheconsole,wegottheaboveoutput. NextTopicPerlCreateExcelFile ←prev next→ ForVideosJoinOurYoutubeChannel:JoinNow Feedback SendyourFeedbackto[email protected] HelpOthers,PleaseShare LearnLatestTutorials Splunk SPSS Swagger Transact-SQL Tumblr ReactJS Regex ReinforcementLearning RProgramming RxJS ReactNative PythonDesignPatterns PythonPillow PythonTurtle Keras Preparation Aptitude Reasoning VerbalAbility InterviewQuestions CompanyQuestions TrendingTechnologies ArtificialIntelligence AWS Selenium CloudComputing Hadoop ReactJS DataScience Angular7 Blockchain Git MachineLearning DevOps B.Tech/MCA DBMS DataStructures DAA OperatingSystem ComputerNetwork CompilerDesign ComputerOrganization DiscreteMathematics EthicalHacking ComputerGraphics SoftwareEngineering WebTechnology CyberSecurity Automata CProgramming C++ Java .Net Python Programs ControlSystem DataMining DataWarehouse JavatpointServicesJavaTpointofferstoomanyhighqualityservices.Mailuson[email protected],togetmoreinformationaboutgivenservices.WebsiteDesigningWebsiteDevelopmentJavaDevelopmentPHPDevelopmentWordPressGraphicDesigningLogoDigitalMarketingOnPageandOffPageSEOPPCContentDevelopmentCorporateTrainingClassroomandOnlineTrainingDataEntryTrainingForCollegeCampusJavaTpointofferscollegecampustrainingonCoreJava,AdvanceJava,.Net,Android,Hadoop,PHP,WebTechnologyandPython.Pleasemailyourrequirementat[email protected]Duration:1weekto2weekLike/Subscribeusforlatestupdatesornewsletter
延伸文章資訊
- 1Why is $#ARGV 0? - perl - Stack Overflow
$#ARGV is the count of the array elements so the count of @ARGV here. It is 0 as arrays start at ...
- 2Perl Display And Pass Command Line Arguments With @argv
Perl command line arguments stored in the special array called @ARGV . The array @ARGV contains t...
- 3即時餵資料給程式吃 - 朝陽科技大學
Perl 會把使用者敲在命令列上的參數放在@ARGV 陣列裡。 (熟悉C 語言的讀者請注意: 在perl 當中, $ARGV[0] 是第一個參數, 不是命令名稱) 程式執行方式(以count_a...
- 4[Perl 筆記] 預設變數@ARGV - 叮咚- 痞客邦
學習記錄﹞- Perl – 預設變數預設變數: $_ , @_, @ARGV @ARGV: 存放命令列引數的陣列$#ARGV: 陣列最後一個索引值執行程式時後面.
- 5Perl的命令行参数和ARGV - 骏马金龙- 博客园
perl将perl命令行的参数列表放进数组ARGV(@ARGV)中。既然是数组,就可以访问($ARGV[n])、遍历,甚至修改数组元素; ARGV数组分三种情况收集:.