Perl Command Line Arguments | argv - Javatpoint

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

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



請為這篇文章評分?