How to execute Unix/shell commands in a Perl script?

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

How to execute Unix/shell commands in a Perl script? · 1. exec”” · 2. system() · 3. Backticks “ or qx// · 4. IPC::Open2 · 5. IPC::Open3. Connectwithus Share Tweet BioPerlisacollectionofPerlmodulesthatareusedtowritePerlscriptsappliedinbioinformatics[1].Itisusedinbioinformaticsprogrammingssuchasindevelopingsourcecodes,standalonesoftware/tools,andalgorithms.It’seasytoinstallandprovidevariousmoduleswhichmakeiteasiertoexecutedifferentfunctions.However,PythonismostlypreferredoverthePerllanguage,still,someofthebioinformaticssoftwareisbasedonPerlsuchasthestandaloneversionofI-TASSER.Sometimes,it’sabigtroubletoexecutesomeUnix/shellcommandsinPerlscriptforthebeginners,it’sdifficulttodecidewhichfunctionwouldbespecifictoacondition.Therefore,thisarticleisaguidefortheexecutionofUnix/shellcommandsinPerlscript. Perloffersdifferentfunctionsandoperatorstoexecuteexternalcommands(describedasfollows),whicharespecialintheirownways.Theyareslightlydifferentfromeachother,whichsometimesmakesithardtochooseforthebeginnersinPerl. 1.exec””  syntax: exec"command"; ItisaPerlfunction(perlfunc)whichexecutesacommandbutneverreturns,assameasthereturnstatementinafunction.Itkeepscontinuingprocessingthescriptwhileexecutingthecommandanddoesn’twaitforittofinishfirst,itreturnsfalsewhenthecommandisnotfoundbutneverreturnstrue. 2.system() syntax: system("command"); ItisalsoaPerlfunction(perlfunc)thatexecutesacommandandwaitsforittogetfinishedfirstandthenresumethePerlscript.Thereturnvalueistheexitstatusofthecommand.Itcanbecalledintwoways: system("commandarg1arg2"); OR system("command","arg1","arg2"); 3.Backticks“orqx// syntax: `command`; syntax: qx/command/; ItisaPerloperator(perlop)verysimilartosystem(),executeacommand,andthenresumesthePerlscriptaftertheexecutionhasfinishedbutthereturnvalueisSTDOUTofthecommand. 4.IPC::Open2 syntax: $output=open2(\*CHLD_OUT,\*CHLD_IN,'commandarg1arg2'); ItrunsaprocessforbothreadingandwritingandcreatesapipetobothSTDINandSTDOUT.Itcanbeusedinbothways: $output=open2(my$out, my$in,'commandarg1arg2'); ORwithoutusingtheshell $output=open2(my$out, my$in,'command','arg1','arg2'); Youcanreadaboutitmoreinthedocumentation: IPC::Open2. 5.IPC::Open3 syntax: $output= open3(\*CHLD_IN,\*CHLD_OUT,\*CHLD_ERR, 'commandarg1arg2','optarg',...); ItisverysimilartoIPC::Open2withthecapabilitytocaptureallthreefilehandlesoftheprocess,i.e.,STDIN,STDOUT,andSTDERR.Itcanalsobeusedwithorwithouttheshell.Youcanreadaboutitmoreinthedocumentation:IPC::Open3. $output=open3(my$out, my$in,'commandarg1arg2'); ORwithoutusingtheshell $output=open3(my$out, my$in,'command','arg1','arg2'); a2p syntax: a2p[options][awkscript] ThereisaPerlutilityknownasa2pwhichtranslatesawkcommandtoPerl.IttakesawkscriptasinputandgeneratesacomparablePerlscriptastheoutput.Suppose,youwanttoexecutethefollowingawkstatement awk'{$1="";$2="";print}'f1.txt Thisstatementgiveserrorsometimesevenafterescapingthevariables(\$1,\$2)butbyusinga2pitcanbeeasilyconvertedtoPerlscript: #!/usr/local/bin/perl eval'exec/usr/local/bin/perl-S$0${1+"[email protected]"}' if$running_under_some_shell; #thisemulates#!processingonNIHmachines. #(remove#!lineaboveifindigestible) eval'$'.$1.'$2;'while$ARGV[0]=~/^([A-Za-z_0-9]+=)(.*)/&&shift; #processanyFOO=barswitches $,='';#setoutputfieldseparator $\="\n";#setoutputrecordseparator while(<>){ chomp;#striprecordseparator @Fld=split('',$_,-1); if($awk){ $Fld[(1)-1]=''; $Fld[(2)-1]=''; printjoin($,,@Fld); } printjoin($,,@Fld)if$f1..$txt; } Forfurtherinformation,youcanreadit’sdocumentation:a2p References Stajich,J.E.;Block,D.;Boulez,K.; Brenner,S.;Chervitz,S.;Dagdigian,C.;Fuellen,G.;Gilbert,J.;Korf,I.;Lapp,H.;Lehväslaiho,H.;Matsalla,C.;Mungall,C.J.;Osborne,B.I.;Pocock,M.R.;Schattner,P.;Senger,M.; Stein,L.D.;Stupka,E.;Wilkinson,M.D.; Birney,E. (2002). “TheBioPerlToolkit:PerlModulesfortheLifeSciences”. GenomeResearch. 12(10):1611–1618. RelatedTopics: UpNext Linux‘sed’commandinPerlprogramming Don'tMiss WhatisNumericalTaxonomy?Howisituseful? TariqAbdullah TariqisfounderofBioinformaticsReviewandCEOatIQLTechnologies.Hisareasofexpertiseincludealgorithmdesign,phylogenetics,MicroArray,PlantSystematics,andgenomedataanalysis.Ifyouhavequestions,reachouttohimviahishomepage. Advertisement Youmaylike 1Comment 1Comment [email protected] November10,2021at2:24am Ihavebeenusingqqtorunlinuxprogramsinsideperl. Anditworkswell. systemqq($adduser–home$home–gecos“$fullname”$username); systemqq($edquota-pjohn$username); systemqq($chage-E\$(date-d+180days+%Y-%m-%d)$username); systemqq($chage-l$username); systemqq($quota-s$username); LogintoReply Youmustbeloggedintopostacomment Login LeaveaReplyCancelreplyYoumustbeloggedintopostacomment. BioinformaticsProgramming vs_analysis_compound.py:Pythonscripttosearchforbindingaffinitiesbasedoncompoundnames. Published1monthagoonSeptember17,2022 ByDr.MunibaFaiza Previously,wehaveprovidedthevs_analysis.pyscripttoanalyzevirtualscreening(VS)resultsobtainedfromAutodockVina.Inthisarticle,wehaveprovidedanotherscripttosearchforbindingaffinityassociatedwithacompound.(more…) ContinueReading BioinformaticsProgramming HowtodownloadfilesfromanFTPserverusingPython? Published1monthagoonSeptember9,2022 ByDr.MunibaFaiza Inthisarticle,weprovideasimplePythonscripttodownloadfilesfromanFTPserverusingPython.(more…) ContinueReading BioinformaticsProgramming HowtoconvertthePDBfiletoPSFformat? Published2monthsagoonAugust29,2022 ByDr.MunibaFaiza VMDallowsconvertingPDBtoPSFformatbutsometimesitgivesmultipleerrors.Therefore,inthisarticle,wearegoingtoconvertPDBintoPSFformatusingadifferentmethod.(more…) ContinueReading LATESTISSUECLICKHERETOREADSPECIALDOCKINGISSUE ADVERT TweetsbyBioinfoReview Login SignUp Rememberme ForgotPassword? SignIn IaccepttheTermsofServiceandPrivacyPolicy SignUp Lostyourpassword?Pleaseenteryourusernameoremailaddress.Youwillreceivealinktocreateanewpasswordviaemail. EmailResetLink



請為這篇文章評分?