Running external programs from Perl with system

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

Shell expansion. Let's say you have a program called checkfiles that can check the files listed on its command line. You could call it ... Togglenavigation PerlMaven PerlTutorial Pro Login Register Books Typekeyword: Archive About Perltutorial Introduction InstallingandgettingstartedwithPerl TheHash-bangline,orhowtomakeaPerlscriptsexecutableonLinux PerlEditor HowtogetHelpforPerl? Perlonthecommandline CorePerldocumentationandCPANmoduledocumentation POD-PlainOldDocumentation DebuggingPerlscripts Scalars CommonWarningsandErrormessagesinPerl Prompt,readfromSTDIN,readfromthekeyboardinPerl AutomaticstringtonumberconversionorcastinginPerl Conditionalstatements,usingif,else,elsifinPerl BooleanvaluesinPerl Numericaloperators Stringoperators:concatenation(.),repetition(x) undef,theinitialvalueandthedefinedfunctionofPerl StringsinPerl:quoted,interpolatedandescaped Heredocuments,orhowtocreatemulti-linestringsinPerl Scalarvariables ComparingscalarsinPerl Stringfunctions:length,lc,uc,index,substr NumberGuessinggame whileloop ScopeofvariablesinPerl Short-circuitinbooleanexpressions Files HowtoexitfromaPerlscript? Standardoutput,standarderrorandcommandlineredirection Warningwhensomethinggoeswrong Whatdoesdiedo? WritingtofileswithPerl Appendingtofiles Openandreadfromtextfiles Don'tOpenFilesintheoldway ReadingandwritingbinaryfilesinPerl EOF-EndoffileinPerl tellhowfarhavewereadafile seek-movethepositioninthefilehandleinPerl slurpmode-readingafileinonestep ListsandArrays Perlforloopexplainedwithexamples PerlArrays Processingcommandlinearguments-@ARGVinPerl HowtoprocesscommandlineargumentsinPerlusingGetopt::Long AdvancedusageofGetopt::Longforacceptingcommandlinearguments Perlsplit-tocutupastringintopieces HowtoreadaCSVfileusingPerl? join Theyearof19100 ScalarandListcontextinPerl,thesizeofanarray Readingfromafileinscalarandlistcontext STDINinscalarandlistcontext SortingarraysinPerl Sortingmixedstrings UniquevaluesinanarrayinPerl ManipulatingPerlarrays:shift,unshift,push,pop ReversePolishCalculatorinPerlusingastack UsingaqueueinPerl Reverseanarray,astringoranumber TheternaryoperatorinPerl Loopcontrols:next,last,continue,break min,max,suminPerlusingList::Util qw-quoteword Subroutines SubroutinesandfunctionsinPerl PassingmultipleparameterstoafunctioninPerl VariablenumberofparametersinPerlsubroutines ReturningmultiplevaluesoralistfromasubroutineinPerl Understandingrecursivesubroutines-traversingadirectorytree Hashes HashesinPerl CreatingahashfromanarrayinPerl Perlhashinscalarandlistcontext exists-checkifakeyexistsinahash deleteanelementfromahash HowtosortahashinPerl? CountthefrequencyofwordsintextusingPerl RegularExpressions IntroductiontoRegexesinPerl5 Regexcharacterclasses Regex:specialcharacterclasses Perl5RegexQuantifiers trim-removingleadingandtrailingwhitespaceswithPerl Perl5RegexCheatsheet Shellrelatedfunctionality Whatare-e,-z,-s,-M,-A,-C,-r,-w,-x,-o,-f,-d,-linPerl? CurrentworkingdirectoryinPerl(cwd,pwd) RunningexternalprogramsfromPerlwithsystem qxorbackticks-runningexternalcommandandcapturingtheoutput Howtoremove,copyorrenameafilewithPerl Readingthecontentofadirectory Traversingthefilesystem-usingaqueue CPAN DownloadandinstallPerl InstallingaPerlModulefromCPANonWindows,LinuxandMacOSX Howtochange@INCtofindPerlmodulesinnon-standardlocations Howtoaddarelativedirectoryto@INC ExamplesforusingPerl HowtoreplaceastringinafilewithPerl HowtoreadanExcelfileinPerl HowtocreateanExcelfilewithPerl? SendingHTMLe-mailusingEmail::Stuffer Perl/CGIscriptwithApache2 JSONinPerl SimpleDatabaseaccessusingPerlDBIandSQL ReadingfromLDAPinPerlusingNet::LDAP Commonwarningsanderrormessages Globalsymbolrequiresexplicitpackagename VariabledeclarationinPerl Useofuninitializedvalue BarewordsinPerl Name"main::x"usedonlyonce:possibletypoat... Unknownwarningscategory Can'tusestring(...)asanHASHrefwhile"strictrefs"inuseat... SymbolicreferencesinPerl Can'tlocate...in@INC Scalarfoundwhereoperatorexpected "my"variablemasksearlierdeclarationinsamescope Can'tcallmethod...onunblessedreference Argument...isn'tnumericinnumeric... Can'tlocateobjectmethod"..."viapackage"1"(perhapsyouforgottoload"1"?) Uselessuseofhashelementinvoidcontext Uselessuseofprivatevariableinvoidcontext readline()onclosedfilehandleinPerl Possibleprecedenceissuewithcontrolflowoperator Scalarvalue...betterwrittenas... substroutsideofstringat... Haveexceededthemaximumnumberofattempts(1000)toopentempfile/dir Useofimplicitsplitto@_isdeprecated... Other MultidimensionalarraysinPerl MultidimensionalhashesinPerl MinimalrequirementtobuildasaneCPANpackage Statementmodifiers:reversedifstatements Whatisautovivification? FormattedprintinginPerlusingprintfandsprintf RunningexternalprogramsfromPerlwithsystem system Prev Next InmanycasesPerlisusedasawrapperaroundotherprograms. ThismeansthatwerunthoseotherprogramsfromourPerlprogram. ForexampleweusePerltocollecttheparametersneededbythatprogram tomakeiteasierforustocreatethecorrectcommandlinetorunthe otherprogram. Inothercaseswemightwanttocapturetheoutputofanothercommandline programandthenmakesomedecisionsbasedonthatoutput. Perlprovidesuswithmanydifferentsolutions.We'llseesomeofthemhere. system Probablythemostsimpleoneiscalledsystem.Initsmostbasic forminacceptsastringthatcontainsexactlywhatyouwouldwriteon thecommandlineinordertoinvoketheexternalcommand. ForexampleonUnix/Linuxmachinesthereisacommandcalled"adduser", thatcancreateauseraccount. Youcouldinvokeitlikethis: /usr/sbin/adduser--home/opt/bfoo--gecos"FooBar"bfoo SoifI'dliketorunthisfromaperlscriptIcanwritethefollowing: system('/usr/sbin/adduser--home/opt/bfoo--gecos"FooBar"bfoo'); Thiswillruntheaddusercommand.Anyoutputorerrorthe addusergenerateswillenduponyourscreen. Youcanalsobuildupthecommandyou'dliketoexecute. Thefollowingtwoexamplesgiveyouthesameresults. my$cmd='/usr/sbin/adduser--home/opt/bfoo--gecos"FooBar"bfoo'; system($cmd); my$cmd='/usr/sbin/adduser'; $cmd.='--home/opt/bfoo'; $cmd.='--gecos"FooBar"bfoo'; system($cmd); systemwithmultiplearguments Thesystemfunctioncanreceivemorethanonearguments. Theaboveexamplecouldhavebeenwrittenlikethis: my@cmd=('/usr/sbin/adduser'); push@cmd,'--home'; push@cmd,'/opt/bfoo'; push@cmd,'--gecos', push@cmd,'FooBar', push@cmd,'bfoo'; system(@cmd); Inthiscasealltheabovesolutionsprovidethesameresult,butit isnotalwaysthecase. Shellexpansion Let'ssayyouhaveaprogramcalledcheckfilesthatcancheckthefiles listedonitscommandline.Youcouldcallitcheckfilesdata1.txtdata2.txt orcheckfilesdata*.txttocheckallthefilesthathasanamestaring withthe4letters'data',followedbysomeothercharactersand havingthe'txt'extension. ThissecondwayofrunningtheprogramwouldworkonUnix/Linuxsystemswhere theshellexpandsthe'data*.txt'toallthefilesthatmatchthedescription. Whentheprogramcheckfilesisexecuteditalreadyseesthelistoffiles: checkfilesdata1.txtdata2.txtdata42.txtdatabase.txt. NotsoofWindows,wherethecommandlinedoesnotdothisexpansion. OnWindowstheprogramwillget'data*.txt'asinput. WhathasittodowithyourPerlscript?Youask. OnWindowsitwon'tmatter. OnUnix/Linuxhowever,ifyourunthe'checkfiles'programfromwithinaPerlscript asonestring:system("checkfilesdata*.txt"),thenPerlwillpass thatstringtotheshell.Theshellwilldoitsexpansionandthe'checkfiles'program willseethelistoffile.Ontheotherhand,ifyoupassthecommandandparameters asseparatestrings:system("checkfiles","data*.txt")thenperlwillrunthe 'checkfiles'programdirectlyandpassthesingleparameter'data*.txt'toitwithout anyexpansion. Asyoucansee,passingthewholecommandasasinglestringhasitsadvantages. Thisadvantagecomeswithapricethough. Thesecurityrisk Callingsystemwithasingleparameterandpassingthewholecommandthatway, canbeasecurityhazardiftheinputcancomefromuntrustedsources.Forexample directlyfromawebform.Orfromthelogfilecreatedbyawebserver. Let'ssayyouaccepttheparameterofcheckfilesfromanuntrustedsource: my$param=get_from_a_web_form(); my$cmd="checkfiles$param"; system($cmd); Iftheusertypesin'data*.txt'thenyouareok.The$cmdwillcontain checkfiledata*.txt. Ontheotherhandiftheuserpassesinsomeother,more'clever'parametersthenyoumight beintrouble.Forexampleiftheusertypesin data*.txt;[email protected]. commentspoweredbyDisqus Ifyouhaveanycommentsorquestions,feelfreetopostthemonthesourceofthispageinGitHub.SourceonGitHub. Commentonthispost Author:GaborSzabo GaborwhorunsthePerlMavensitehelpscompaniessetuptestautomation,CI/CD ContinuousIntegrationandContinuousDeploymentandotherDevOpsrelated systems. GaborcanhelprefactoryouroldPerlcode-base. HerunsthePerlWeeklynewsletter. ContactGaborifyou'dliketohirehisservice. BuyhiseBooksorifyoujustwouldliketosupporthim,doitviaPatreon. English Русский 简体中文 aboutthetranslations documentationofsystem



請為這篇文章評分?