Perl Introduction
文章推薦指數: 80 %
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=;
#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@<<
延伸文章資訊
- 1Perl on UNIX and Linux Systems - The Perl Beginners' Site
Learn Perl Now! And get a job doing Perl. If you are using a UNIX-compatible system (such as Linu...
- 2Linux perl command help and examples - Computer Hope
"Perl" officially stands for "Practical Extraction and Report Language." It was originally a lang...
- 3新手上路指南 - 朝陽科技大學
建議Windows 使用者最好安裝cygwin 及上面的perl。 你也可以單獨安裝windows 版perl (見下面) 但cygwin 環境提供類似unix 命令列的環境, 下許多指令比較方便。
- 4Perl for Unix System Administration - 博客來
書名:Perl for Unix System Administration,語言:英文,ISBN:1884777821,作者:O'Neill, Brian T.,出版日期:2000/02/01...
- 5Perl Introduction
Perl is a script language, which is compiled each time before running. That unix knows that it is...