Perl Introduction

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

Perl is a script language, which is compiled each time before running. That unix knows that it is a perl script there must be the following header at the ... Introduction toPerlProgramming(perl5) Contents Basics VariablesandOperators Branching Looping FileTestOperators RegularExpressions InputandOutput ProcessingfilesmentionedontheCommandline GetFilenames Pipeinputandouputfrom/toUnixCommands ExecuteUnixCommands ThePerlbuiltinFunctions Subroutines SomeofthespecialVariables Forking BuildingPipesforforkedChildren BuildingaSocketConnectintoanotherComputer GetUserandNetworkInformation Arithmetics FormattingOutputwith"format" CommandlineSwitches FullPerl5Documentation Basics Scripts Perlisascriptlanguage,whichiscompiledeachtimebeforerunning. Thatunixknowsthatitisaperlscripttheremustbethefollowingheader atthetoplineofeveryperlscript:#!/usr/bin/perl wherethepathtoperlhastobecorrectandthelinemustnotexeed 32charachters. CommentsandCommands Aftertheheaderline:#!/usr/bin/perlthere areeitheremptylineswithnoeffectorcommandlinesorcommentarylines. Everythingfromandbehinda"#"up totheendofthelineiscommentandhasnoeffectontheprogram.Commands startwiththefirstnonspacecharachteronalineandendwitha";". Soonecancontinueacommandoverseverallinesandterminatesitonly withthesemicolon. Directcommandsandsoubroutines Normalcommandsareexecutedintheorderwritteninthescript.Butsoubroutines canbeplacedanywhereandwillonlybeevaluatedwhencalledfromanormal commandline.Perlknowsit'sasoubroutineifitthecodeispreceeded witha"sub"andenclosedinablocklike:sub name{command;} Otherspeciallines Perlcanincludeotherprogrammingcodewith:require somethingorwithusesomething. Quotations Singlequote:''or:q// Doublequote:""or:qq// Quoteforexecution:``or:qx// Quotealistofwords:('term1','term2','term3') or:qw/term1term2term3/ Quoteaquotedstring:qq/"$name"is$name/; Quotesomethingwichcontains"/":qq!/usr/bin/$file isreaddy!; Scalarandlistcontext Thatperldistinguishesbetweenscalarandlistcontextisthebigfeature, whichmakesituniqeandmoreusfulthenmostotherscriptlanguages. AsoubroutinecanreturnlistsandnotonlyscalarslikeinC.Oranarray givesthenumberofelementsinascalarcontextandtheelementsitself inalistcontext. Theenormousvalueofthatfeatureshouldbeevident. VariablesandOperators General Therearescalarvariables,oneandtwodimensionalarraysandassociative arrays.Insteadofdeclaringavariableonepreceedsitwithaspcialcharachter. $variableisanormalscalarvariable. @variableisanarrayand%variable isanassociativearray.Theuserofperldoesnothavetodistinguish betweenanumberandastringinavariable.Perlswitchesthetypeif neccessary. Scalars Fillinascalarwith:$price=300;$name="JOHN"; Calculatewithitlike:$price*=2;$price =$oldprice*4;$count++;$worth--;Printoutthevalueof ascalarwith:print$price,"\n"; Arrays Fillinavalue:$arr[0]="Fred";$arr[1]="John"; Printoutthisarray:printjoin('',@arr),"\n"; Iftwodimensional:$arr[0][0]=5;$arr[0][1] =7; Hashes(AssociativeArrays) Fillinasingleelementwith:$hash{'fred'}= "USA";$hash{'john'}="CANADA"; Fillintheentirehash: %a=(    'r1', 'thisisvalofr1',    'r2', 'thisisvalofr2',    'r3', 'thisisvalofr3', ); orwith: %a=(    r1=>'thisisvalofr1',    r2=>'thisisvalofr2',    r3=>'thisisvalofr3', ); Assignements Putsomethingintoavariablewitha"=" orwithsomecombinedoperatorwhichassignesandanddoessomethingat thesametime: $var="string";Putsthestringinto $var $var=5;Putsanumberinto$var $var.="string";Appendsstringto $var $var+=5;Addsnumberto$var $var*=5;Multipliywith5 $var||=5;If$varis0makeit5 $varx=3;Make$vartothreetimes $varasstring:fromatoaaa Modifyandassignewith: ($new=$old)=~s/pattern/replacement/; Comparisons Comparestringswith:eqnelike in:$nameeq"mary". Comparenumberswith:==!=>=<=<=> likein:$price==400. And/Or/Not Acctonsuccessorfailureofanexpression:$yes ordie;meansexitif$yesisnotset. ForANDwehave:&&and"and" andforORwehave:||or"or". Notis"!"or"not". AND,ORandNOTareregularlyusedinif()statements: if($first&&$second){....;} if($first||$second){....;} if($first&&!$second{....;} meansthat$firstmustbenonzerobut$secondmustnotbeso. ButmanyNOT'scanbehandledmorereasonablewiththeunless()statement. Instead: printif!$noway;oneuses:print unless$noway; . Branching if if(condition){    command; }elsif(condition){    command; }else{    command; } commandifcondition; unless(justtheoppositeofif) unless(condition){    command; }else{    command; } commandunlesscondition; Looping while while(condition){    command; } #Goprematurelytothenextiteration while(condition){    command;    nextifcondition;    command; } #Prematureleyaborttheloopwithlast while(condition){    command;    lastifcondition; } #Prematureleycontinuetheloopbutdocontinue{}inanycase while(condition){    command;    continueifcondition;    command; }continue{    command; } #Redotheloopwithoutevaluatingwhile(condtion) while(condtion){    command;    redoifcondition; } commandwhilecondition; until(justtheoppositeofwhile) until(condition){    command; } until(condition){    command;    nextifcondition;    command; } until(condition){    command;    lastifcondition; } until(condition){    command;    continueifcondition;    command; }continue{    command; } commanduntilcondtion; for(=foreach) #Iterateover@dataandhaveeachvaluein$_ for(@data){    print$_,"\n"; } #Geteachvalueinto$infoiteratively for$info(@data){    print$info,"\n"; } #Iterateoverarangeofnumbers for$num(1..100){    nextif$num%2;    print$num,"\n"; } #Eternalloopwith(;;) for(;;){    $num++;    lastif$num>100; } map #syntax map(command,list); map{comm1;comm2;comm3;}list; #example map(rename($_,lc($_),); . FileTestOperators Filetestoperatorscheckforthestatusofafile:Someexamples: -f$file It'saplainfile -d$file It'sadirectory -r$file Readablefile -x$file Executablefile -w$file Writablefile -o$file Weareowner -l$file Fileisalink -e$file Fileexists -z$file Filehaszerosize,butexists -s$file Fileisgreaterthanzero -tFILEHANDLE Thisfilehandleisconnetctedtoatty -T$file Textfile -B$file Binaryfile -M$file Returnsthedaynumberoflastmodificationtime RegularExpressions Whatitis Aregularexpressionisanabstractformulationofastring.Usuallyone hasasearchpatternandamatchwhichisthefoundstring.Thereisalso areplacementforthematch,ifasubstitutionismade. Patterns Apatternstandsforeitherone,anynumber,several,aparticularnumber ornonecasesofacharacteroracharachter-setgivenliteraly,abstractly oroctaly. PATTERN MATCH . anycharacter(dot) .* anynumberonanycharacter(dotasterix) a* themaximumofconsecutivea's a*? theminimumofconsecutivea's .? oneornoneofanycharacters .+ oneormoreofanycharacter .{3,7} threeuptosevenofanycharacters,butasmanyaspossible .{3,7}? threeuptoseven,butthefewestnumberpossible .{3,} atleast3ofanycharachter .{3} exactly3timesanycharacter [ab] aorb [^ab] notaandalsonotb [a-z] anyofathroughz ^a \Aa aatbeginingofstring a$ a\Z aatendofstring A|bb|CCC AorbborCCC tele(f|ph)one telefoneortelephone \w A-Zora-zor_ \W noneoftheabove \d 0-9 \D noneof0-9 \s spaceor\tor\n(whitespace) \S nonspace \t tabulator \n newline \r carridgereturn \b wordboundary \bkey matcheskeybutnothousekey (?#.......) Comment (?i) Caseinsensitivematch.Thiscanbeinsideapatternvariable. (?:a|b|c) aorborc,butwithoutstringin$n (?=.....) Match.....butdonotstorein$& (?!.....) Anythingbut.....anddonotstorein$& Substitututions Onecanreplacefoundmatcheswithareplacementwiththes/pattern/replacement/; statement. The"s"isthecommand.Thentherefollowthreedelimiterswithfirsta searchpatternandsecondareplacementbetweenthem.Ifthereare"/" withingthepatternorthereplacementthenonechoosesanotherdelimiter than"/"forinstancea"!". Tochangethecontentofavariabledo:$var=~ s/pattern/replacement/; Toputthechangedvalueintoanothervariable,withoutdistortingthe originalvariabledo: ($name=$line)=~s/^(\w+).*$/$1/; COMMAND WHATitDOES s/A/B/; substitutethefirstainastringwithB s/A/B/g; substituteeveryawithaB s/A+/A/g; substituteanynumberofawithoneA s/^#//; substitutealeading#withnothing.i.eremoveit s/^/#/; prependa#tothestring s/A(\d+)/B$1/g; substituteafollowedbyanumberwithbfollowedbythesamenumber s/(\d+)/$1*3/e; substitutethefoundnumberwith3timesit'svalue Usetwo"e"fortogetanevaleffect: perl-e'$aa=4;$bb='$aa'; $bb=~s/(\$\w+)/$1/ee;print$bb,"\n";' s/heregoesdate/$date/g; substitute"heregoesdate"withthevalueof$date s/(Masumi)(Nakatomi)/$2$1/g; switchthetwoterms s/\000//g; removenullcharachters s/$/\033/; appenda^Mtomakeitreadablefordos InputandOutput Outputavaluefromavariable print$var,"\n"; Outputaformatedstring printf("%-20s%10d",$user,$wage); Readinavalueintoavariableandremovethenewline chomp()(perl5)removesanewlineifoneisthere.Thechop()(perl4)removes anylastcharacter. chomp($var=); Readinafileanprocessitlinewise open(IN,"){    command; } closeIN; Readafileintoanarray open(AAA,"; closeAAA; Outputintoafile open(OUT,">file")||die"Cannotobenfileforoutput\n"; while(condition){    printOUT$mystuff; } closeOUT; Check,whetheropenfilewouldyieldsomething(eof) open(IN,"){        print;    } } closeIN; ProcessFilesmentionedontheCommandline Theemptyfilehandle"<>"readsineachfileiteratively.Thenameof thecurrentprocessedfileisin$ARGV.Forexampleprinteachlineof severalfilesprependedwithit'sfilename: while(<>){    $file=$ARGV;    print$file,"\t",$_;    open(IN,"; Usecurrentdirectoryiteratively while(){    ...commands... } Selectfileswith<> @files=; Selectfileswithglob() Thisistheofficialwayofglobbing: @files=glob("$mypatch/*$suffix"); Readdir() Perlcanalsoreadadirectoryitself,withoutaglobbingshell.Thisis fasterandmorecontrollable,butonehastouseopendir()andclosedir(). opendir(DIR,".")ordie"Cannotopendir.\n"; while(readdirDIR){    rename$_,lc($_);  } closedir(DIR); PipeInputandOutputfrom/toUnix Commands ProcessDatafromaUnixPipe open(IN,"unixcommand|")||die"Couldnotexecuteunixcommand\n"; while(){    command; } closeIN; OutputDataintoaUnixPipe open(OUT,"|more")||die"Couldnotopenthepipetomore\n"; for$name(@names){    $length=length($name);    printOUT"Thename$nameconsistsof$lenghtcharacters\n"; } closeOUT; ExecuteUnixCommands ExecuteaUnixCommandandforgetabouttheOutput system("someprog-auexe-fv$filename"); ExecuteaUnixCommandanstoretheOutputintoaVariable Ifit'sjustonelineorastring: chomp($date=qx!/usr/bin/date!);The chomp()(perl5)removesthetrailing"\n".$dategetsthedate. Ifitgivesaseriesoflinesoneput'stheoutputintoanarray: chomp(@alllines=qx!/usr/bin/who!); Replacethewholeperlprogrambyaunixprogram execanotherprog;Butthentheperl programisgone. ThePerlbuiltinFunctions StringFunctions Getalluppercasewith:  $name=uc($name); Getonlyfirstletteruppercase:  $name=ucfirst($name); Getalllowercase:  $name=lc($name); Getonlyfirstletterlowercase:  $name=lcfirst($name); Getthelengthofastring: $size=length($string); Extract5-thto10-thcharactersfromastring: $part=substr($whole,4,5); Removelineending: chomp($var); Removelastcharacter: chop($var); Cryptastring: $code=crypt($word,$salt); Executeastringasperlcode: eval$var; Showpositionofsubstringinstring: $pos=index($string,$substring); Showpositionoflastsubstringinstring: $pos=rindex($string,$substring); Quoteallmetacharachters: $quote=quotemeta($string); ArrayFunctions Getexpressionsforwhichacommandreturnedtrue: @found=grep(/[Jj]ohn/,@users); Applayacommandtoeachelementofanarray: @new=map(lc($_),@start); Putallarrayelementsintoasinglestring: $string=join('',@arr); Splitastringandmakeanarrayoutofit: @data=split(/&/,$ENV{'QUERY_STRING'}; Sortanarray: sort(@salery); Reverseanarray: reverse(@salery); Getthekeysofahash(associativearray): keys(%hash); Getthevaluesofahash: values(%hash); Getkeyandvalueofahashiteratively: each(%hash); Deleteanarray: @arr=(); Deleteanelementofahash: delete$hash{$key}; Checkforahashkey: if(exists$hash{$key}){;} Checkwetherahashhaselements: scalar%hash; Cutoflastelementofanarrayandreturnit: $last=pop(@IQ_list); Cutoffirstelementofanarrayandreturnit: $first=shift(@topguy); Appendanarrayelementattheend: push(@waiting,$name); Prependanarrayelementtothefront: unshift(@nowait,$name); Removefirst2charsanreplacethemwith$var: splice(@arr,0,2,$var); Getthenumberofelementsofanarray: scalar@arr; Getthelastindexofanarray: $lastindex=$#arr; FileFunctions Openafileforinput: open(IN,"/path/file")||die"Cannotopen file\n"; Openforappending: open(OUT,">>$file")||&myerr("Couldn't open$file"); Closeafile: closeOUT; Setpermissions: chmod0755,$file; Deleteafile: unlink$file; Renameafile: rename$file,$newname; Makeahardlink: link$existing_file,$link_name; Makeasymboliclink:  symlink$existing_file,$link_name; Makeadirectory: mkdir$dirname,0755; Deleteadirectory: rmdir$dirname; Reduceafile'ssize: truncate$file,$size; Changeowner-andgroup-ID: chown$uid,$gid; Findtherealfileofasymlink: $file=readlink$linkfile; Getallthefileinfos: @stat=stat$file; ConversionsFunctions Numbertocharacter: chr$num; Charachtertonumber: ord($char); Hextodecimal: hex(0x4F); Octaltodecimal: oct(0700); Getlocaltimefromtime: localtime(time); Getgreenwichmeantime: gmtime(time); Packvariablesintostring: $string=pack("C4",split(/\./,$IP)); Unpacktheabovestring: @arr=unpack("C4",$string); Subroutines(=functionsinC++) DefineaSubroutine submysub{    command; } Example: submyerr{    print"Thefollowingerroroccured:\n";    print$_[0],"\n";    &cleanup;    exit(1); } CallaSubroutine &mysub; GiveArgumentstoaSubroutine &mysub(@data); ReceiveArgumentsintheSubroutine Asglobalvariables: submysub{    @myarr=@_; } submysub{    ($dat1,$dat2,$dat3)=@_; } Aslocalvariables: submysub{    local($dat1,$dat2,$dat3)=@_; } SomeoftheSpecialVariables SYNTAX MEANING $_ Stringfromcurrentloop.e.g.for(@arr){$field=$_."ok";} $. Linenumberfromcurrentfileprocessedwith:while(){ $0 Programname $$ Processidofcurrentprogram $< Therealuidofcurrentprogram $> Effektiveuidofcurrentprogram $| Forflushingoutput:selectXXX;$|=1; $& Thematchofthelastpatternsearch $1.... The()-embracedmatchesofthelastpatternsearch $` Thestringtotheleftofthelastmatch $' Thestringtotherightofthelastmatch Forking Forkingisveryeasy!Justfork.Oneputstheforkinathreewayif(){} toseparatelytheparent,thechildandtheerror. if($pid=fork){    #Parent    command; }elsif($pid==0){    #Child    command;    #Thechildmustendwithanexit!!    exit; }else{    #Error    die"Forkdidnotwork\n"; }   BuildingPipesforforkedChildren BuildingaPipe pipe(READHANDLE,WRITEHANDLE); FlushingthePipe select(WRITEHANDLE);$|=1;select(STDOUT); SettinguptwoPipesbetweentheParentandaChild pipe(FROMCHILD,TOCHILD); select(TOCHILD);$|=1;select(STDOUT); pipe(FROMPARENT,TOPARENT);select(TOPARENT);$|=1;select(STDOUT); if($pid=fork){    #Parent    closeFROMPARENT;    closeTOPARENT;    command; }elsif($pid==0){    #Child    closeFROMCHILD;    closeTOCHILD;    command;    exit; }else{    #Error    command;    exit; } BuildingaSocketConnectiontoanother Computer #Somwhereatthebeginningofthescript require5.002; useSocket; usesigtrap; #Prepareinfos $port  =80; $remote='remotehost.domain'; $iaddr =inet_aton($remote); $paddr =sockaddr_in($port,$iaddr); #Socket socket(S,AF_INET,SOCK_STREAM,$proto)ordie$!; #Flushsocket select(S);$|=1;select(STDOUT); #Connect connect(S,$paddr)ordie$!; #Printtosocket printS"something\n"; #Readfromsocket $gotit=; #Orreadasinglecharacteronly read(S,$char,1); #Closethesocket close(S); GetUnixUserandNetworkInformations Getthepasswordentryforaparticularuserwith:@entry =getpwnam("$user"); OrwithbyeuserID:@entry=getpwuid("$UID"); Onecaninformationsforgroup,host,network,services,protocolsinthe abovewaywiththecommands:getgrnam,getgrid,gethostbyname, gethostbyaddr,getnetbyname,getnetbyaddr,getservbyname,getservbyport, getprotobyname,getprotobynumber. Ifonewantstogetalltheentriesofaparticularcategorieonecanloop throughthemby: setpwent; while(@he=getpwent){ commands... } entpwent; Forexample:Getalistofalluserswiththeirhomedirectories: setpwent; while(@he=getpwent){    printf("%-20s%-30s\n",$he[0],$he[7]); } endpwent; Thesameprincipleworksforalltheabovedatacategories.Butmostof themneeda"stayopen"behindthesetcommand. Arithmetics Addition:+ Subtraction:- Multiplication:* Division:/ Risetothepowerof:** Riseetothepwoerof:exp() Modulus:% Squareroot:sqrt() Absolutvalue:abs() Tangens:atan2() Sinus:sin() Cosine:cos() Randomnumber:rand() FormattingOutputwith"format" Thisshouldbesimplificationoftheprintfformatting.Oneformatsonce onlyandthenitwillbeusedforeverywritetoaspecifiedfilehandle. Prepareaformatsomwhereintheprogram: formatfilehandle= @<<<<<<<<<>>>>>>>>>@|||||||||| $var1,$var3,$var4 . Nowusewritetoprintintothatfilhandleaccordingtotheformat: writeFILEHANDLE; The@<<>>rightadjustment,@##.## isfornumericalsand@|||centers. CommandlineSwitches Showtheversionnumberofperl: perl-v; Checkanewprogramwithoutruningit: perl-wc; Haveaneditingcommandonthecommandline: perl-e'command'; Automaticallyprintwhileprecessinglines: perl-pe'command'; Removelineendingsandaddthemagain: perl-lpe'command'; Editafileinplace: perl-i-pe'command'; Autosplitthelineswhileediting: perl-a-e'printif$F[3]=~/ETH/;'; Haveaninputloopwithoutprinting: perl-ne'command'; FullDocumentation Forprecisedetailsseetheofficialfulldocumentationofperl5.The fileis1Mega.Imadealocalcopyofthefilefornotloosingtraceof it,ifthelinksarechanged. Getthelocalcopyoftheperl5manualnow. Orgetit fromAustraliainahandierformbutwithpossiblyalongerloadingtime Orjustwantsomeoneelse'Perllecture?Getithere:Introduction toPerl ThankstotheO'Reilly &Associates,Inc.'sperlbooksbyLarryWall,RandalSchwartzand J.Vromans. Please emailmeanyideaforanenhancementofthispage.



請為這篇文章評分?