




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、Perl使用介紹,Whats Perl,What is Perl? Practical Extraction Perl Language Pathologically Electric Rubbish Lister Practically Everything Really Likeable shells, awk, sed, grep, C Whats Perl for? Manipulate text in files, extract data from files write reports Multiple Platform,Perl Scripts,Perl at the Comm
2、and Line Script Setup The Script,Perl at the Command Line,Where is Perl? /usr/local/bin The -e switch : 由Command Line執(zhí)行Perl $ perl -e print “hello dollyn”; The -n Switch:對(duì)檔案的每一行執(zhí)行相同的動(dòng)作 Example 1 The -c Switch: 檢查Script的語(yǔ)法 $ perl -ce print if /Igor emp.first $ perl -ce print if /Igor/ emp.first,Scrip
3、t Setup,Statements are terminated with a semicolon(;) 只有子程式(subroutine)與報(bào)告(report format)需要先宣告 Variable不需先宣告 Initialize 為 0 或 空字串 (),The Script,Startup: Script 的第一行寫(xiě)上 #! #!/usr/local/bin/perl Comments: # Sample Script: ex2.perl 如果第一行沒(méi)加上 #! ? perl ,Printing,File Handle Words The print Function The pr
4、intf Function,File Handle,The three predefined file handles: : Standard Input : Standard Output : Standard Error The print and printf functions send their output by default to the STDOUT filehandle,Words,大小寫(xiě)不同(case sensitive) Quotes 單引號(hào):不做任何變數(shù)或特殊字元的轉(zhuǎn)換 雙引號(hào) $, $, , %,常數(shù)(Literal, Constant),數(shù)值常數(shù) 12345 0
5、 x456fff (16進(jìn)位) 0777(8進(jìn)位) 23.45 .234E-2 字串常數(shù) t n r f b a e 033 xff l u L U E ,常數(shù)(Cont.),特殊常數(shù) _LINE_ : Current Line Number _FILE_ : Current File Name _END_ : Logical end of the script; trailing garbage is ignored,The print Function,Example 3 Printing Literals : Example 4, 5,The printf Function,The sa
6、me as in C Format Specifiers (Example 6) c : Character s : String d : Decimal; ld : Long Decimal u : Unsigned Decimal; lu : Long Unsigned Decimal x : Hex; lx : Long Hex o : Octal; lo : Long Octal e : Scientific Notation f : Floating Point g : e or f (which takes the least space),Whats in a Name?,Abo
7、ut Perl variables Scalars, Arrays, and Associative Arrays Reading from STDIN Array Functions Associative Array Functions,About Perl Variables,Types scalar, array, and associative array Scope and Package Default global in scope Naming Conventions $var - Scalar variable var - Array variable %var - Ass
8、ociative variable Case sensitive 初始值為0或空字串,About Perl Variables (Cont.),Example 7 Quoting Rules (Example 8) “” scalar variable 與 array 會(huì)換成該有的值 Associative array 不會(huì)換 t, n, 等一定要包在 “” 內(nèi) : 不會(huì)做任何轉(zhuǎn)換 : 執(zhí)行包在裡頭的指令,Scalar Variables,變數(shù)名稱(chēng)前要加 $ $number = 150;$name = “Jody Savage”;,#!/usr/local/bin/perl $num=5; $
9、friend=“John Smithn”; $money=125.75; $now=date; $month=Jan; print “$numn”; print $friend; print “I need $moneyn”; print qq/$friend gave me $money.n/; print qq/The time is $now/; print “The month is $monthuary.n”;,Array (I),變數(shù)名稱(chēng)前要加 student 要存取Array中的單一元素要用 $ $student4 Array的第一個(gè)元素Index為0 Array中的元素可以是數(shù)
10、值與字串的混合,name = (“Guy”,”Tom”,”Dan”); grades=(100,90,65,96,40,75); items=($a,$b,$c) empty=(); $size=items;,Array (II),$#arrayname = 最後一個(gè)元素的Index $ = 第一個(gè)元素的Index(0) Array可以隨時(shí)增加或減少裡頭的元素 Example 9,$indexsize=$#grades; $#grades=3; $#grades=$ - 1 $grades=(); digits=(0.10); letters=(A.Z);,Associative Arrays
11、,變數(shù)名前要加 % Consists of one or more pairs of scalars The first of the Pair = Key The second of the Pair = Value,%seasons=(Sp,Spring, Su,Summer, F,Fall, W,Winter); %days=(1,Monday, 2,Tuesday, 3,); $days3=Wednesday; $days5=“Friday”; print “Today is $days3.n”; print %seasons,”n”;,Reading from STDIN(I),#!
12、/usr/local/bin/perl print “What is your name? “; $name = ; print “What is your fathers name? “; $paname=; print “Your name is $name.”; print “Your fathers name is $paname.”;,chop = 砍掉字串的最後一個(gè)字元 #!/usr/local/bin/perl print “Hello there, and what is your name? “; $name=; print “$name is a very high cla
13、ss name.n”; chop($name); print “$name is a very high class name.n”; print “Whats your age? “ chop($age=); print “For $age, you look so young!n”;,Reading from STDIN (II),The getc Function print “Answer y or n “; $answer=getc; print “$answern”;,#!/usr/local/bin/perl $course_number=101; print “What is
14、the name of the course 101? “; $course$course_number=; print $course$course_number;,Array Function (I),grep(EXPR,LIST):找出LIST中含有/EXPR/的元素 join(DELIMITER,LIST):將LIST中的所有元素用DELIMITER接起來(lái),list=(tomatos,tomorrow,potatos,phantom,Tommy);$count=grep(/tom/i,list);items=grep(/tom/i,list);print “Found items: i
15、temsn Number found:$countn”; $name=“Joe Blow”;$birth=“11/26/86”;$address=“10 Main St.”;print join(“:”,$name, $birth, $address), “n”;,Array Function (II),pop(ARRAY):Delete the last element and return it push(ARRAY, LIST):Push values onto the end of an array shift(ARRAY): Delete the first element of a
16、n array and return it unshift(ARRAY,LIST):Prepend List to the front of the arrary Example 10,Array Function (III),splice(ARRAY, OFFSET ,LENGTH ,LIST) #!/usr/local/bin/perlcolors=(red,green,purple,blue,brown);print “The original array is colorsn”;newcolors=splice(colors,2,3,yellow,orange);print “The
17、removed items are newcolorsn”;print “The spliced array is now colorsn”;,Array Function (IV),split(/DELIMITER/,EXPR,LIMIT) #!/usr/local/bin/perl$line=“a b c d e”;letter=split( ,$line);print “The first letter is $letter0n”;print “The second letter is $letter1n”; perl -ne str=split(/:/);print $str0,”n”
18、 /etc/passwd Example 11,Array Function (V),reverse(LIST) #!/usr/local/bin/perl names=(“Bob”,”Dan”,”Tom”,”Guy”); print names; reversed=reverse(names),”n”; print “reversedn”;,sort (SUBROUTINE LIST) #!/usr/local/bin/perl string=(4.5,x,68,a,B,c,10,1000,1); string_sort=sort(string); print “string_sortn”;
19、 sub numeric $a $b; number_sort=sort numeric 1000, -22.5, 10, 55, 0; print “number_sort.n”;,Associative Array Functions,keys(ASSOC_ARRAY): Return the key parts values(ASSOC_ARRAY): Return the value parts each(ASSOC_ARRAY): Return the (key, value) delete $ASSOC_ARRAYKEY: Delete the corresponding (KEY
20、, VALUE). The deleted value is returned if successful. Example 12,Operator,Mixing Data Types Introduction to Perl Operators,Mixing Data Types,Perl 會(huì)依狀況作變數(shù)型態(tài)的轉(zhuǎn)換,#!/usr/local/bin/perl $x= 12! + 4n; print $x; print n; $y=ZAP. 5.5; print $yn;,Assignment Operators,#!/usr/local/bin/perl $name=Dan; $line=*
21、; $var=0; $var+=3; print $var+=3 is $var n; $var-=1; print $var-=1 is $var n; $var*=2; print $var squared is $var n;,$var%=3; print The remainder of $var/3 is $var n; $var =2; print $var shift left by two is $var n; $name.=ielle; print $name is the girls version of Dan.; $linex=10; print $linen; pri
22、ntf $var is %.2fn, $var=4.2+4.69;,Relational Operators,Numberic = = String gt (Greater Than) ge (Greater Than or Equal) lt (Less Than) le (Less Than or Equal),$x=5; $y=4; $result = $x $y; print $resultn; $result = $x $y; print $resultn; $fruit1=pear; $fruit2=peaR; $result = $fruit1 gt $fruit2; print
23、 $resultn; $result = $fruit1 lt $fruit2; print $resultn;,Equality Operators,Numeric = (equal) != (not equal) (not equal, signed return) String eq (equal) ne(not equal) cmp (not equal, signed return) Example 13,Logical Operators, $num2=100; $num3=0; print $num1 ,Auto increment/decrement,$x+ = $x=$x+1
24、 Example: $y=$x+ $y=$x $x=$x+1 + $x = $x=$x+1 Example: $y= +$x $x=$x+1 $y=$x $x- = $x=$x-1 -$xx = $x=$x-1,$x=5; $y=0; $y=+$x; print Pre-increment:n; print y is $y.n; print x is $x.n; print -x20,n; $x=5; $y=0; $y=$x+; print Post-increment:n; print y is $y.n; print x is $x.n;,Conditional and Range Ope
25、rator,Conditonal Operator $x ? $y: $z if $x is true, return $y; if $x is false, return $z Example print What is your age? ; chop($age=); $price=($age 60) ? 0:5.55; printf You will pay $%2f.n, $price;,Range Operator Example print 0.10,n; print A.Z,n;,String Operators and Functions,將 $str1 與 $str2接起來(lái)
26、$str1.$str2 將 $str1重複$num times $str1 x $num 將 $str1 自 $offset 起取 $len 個(gè)字元 substr($str1,$offset,$len) 看$str2在$str1中出現(xiàn)的地方 index($str1,$str2) EXPR的長(zhǎng)度 length(EXPR) Example 14,Control Statements,Decision Making Loops,The if Construct,if (expression) Block if (expression) Block else Block if (expression)
27、 Block elsif (Expression) Block else Block Example 15, 16,The unless Construct,unless (expression) Block unless (expression) Block else Block unless (expression) Block elsif (expression) Block else Block,$num1=1; $num2=0; $str1=Hello; $str2=; unless ($num1) print True!n; $x+; unless ($num2) print Fa
28、lse!n; $y+; unless ($str1) print True Again!n; unless ($str2) print False Again!n; print Not Equal!n unless $x = $y;,The while loop,while (expression) Block 只要 (expression) 是True, Block裡頭的指令會(huì)重複執(zhí)行 通常Block中會(huì)含有在某時(shí)候把 (expression)變成False的指令,$num=0; while ($num 10) print $sun ; $num +; print nOut of the L
29、oop.n;,The until loop,until (Expression) Block 只要 (expression) 是False, Block裡頭的指令會(huì)重複執(zhí)行 通常Block中會(huì)含有在某時(shí)候把 (expression)變成True的指令,#!/usr/local/bin/perl $num=0; until ($num = 10) print $num ; $num +; print nOut of the Loop.n;,The dowhile/until Loop,do Block while (expression) do Block until (expression)
30、類(lèi)似 while/until Loop, 但是Block內(nèi)的指令至少會(huì)執(zhí)行一次,$x=1; do print $x ; $x+; while ($x = 10); print n;,The for loop,for (exp1;exp2;exp3) Block exp1;while (exp2)Block; exp3;,for ($i=0; $i 10; $i+) print $i ; print nOut of the Loopn;,The foreach loop,foreach Variable (Array)Block 將Array中每一個(gè)element的值給Variable後執(zhí)行Bl
31、ock指令 Variable的值在執(zhí)行完 foreach之後回復(fù)為原有的值(Local) Example 17,18,foreach $hour (1.24) if ($hour 0 ,Getting a Handle on Files,The User-Defined Filehandle File Testing,The User-Defined Filehandle,Open for Reading: open(HANDLE, NAME) Closing the File Handle: close(HANDLE) Open for Writing: open(HANDLE, “ NAM
32、E”) Open for Appending: open(HANDLE, “ NAME”) Output Pipe: open(HANDLE, “|COMMAND”) Input Pipe: open(HANDLE,”COMMAND|”) Example 19,20,File Testing,$file=perl.test print “File is readablen” if ( -r $file); print “File is writablen” if ( -w $file); print “File is executablen” if ( -x $file); print “Fi
33、le is a regular filen” if ( -f $file); print “File is a directoryn” if ( -d $file); print “File is a text filen” if ( -T $file); print “File is last modified %f days agon” -M $file; print “File has read, write, and execute set.n” if -r $file eof(HANDLE), eof(),Regular Expression,What is a Regular Ex
34、pression?,A regular expression is really just a sequence or pattern of characters matched against a string of text when performing searches and replacement. /abc/ : Match any String ?abc?: 只Match第一次出現(xiàn)的 abc hhhabczzzabckkkabc,The m Operator,用來(lái)尋找Match的字串 Examples m/Good Morning/ /Good Morning/ /usr/ad
35、m/acct/ m#/usr/adm/acct# Examples perl -ne print /Betty/ s perl -ne print unless /Evich s perl -ne print if m#Jon# s,The s Operator,取代Match的字串為新的字串 s/old/new: 只取代每一行的第一個(gè)Match的字串 s/old/new/g: 全部取代 s+old+new+g Examples perl -ne s/Steven/Jane/; print; s perl -ne print if
36、 s/Igor/Ivan/; s perl -ne s#Ivan#Boris#; print s Case Insensitivity m/pattern/i s/old/new/i,Pattern Binding Operators,用在要Match的字串不是 $_ 的情形下 variable = /Expression/ variable ! /Expression/ variable = s/old/new Example 21 Example 22,Subroutines and Packages,Subroutine Definition Passin
37、g Arguments Packages,Subroutine Definition,Subroutine Definition sub subroutine_name Block Subroutine Call: $last=Blenheim; while () ,Local and Return,The Local Function: 定義只在subroutine中用的變數(shù). 出了subroutine後就不見(jiàn)了 local(local_var1, local_var2,) Example 24 Return Value:subroutine最後一個(gè)Expression的值 Example
38、25,Packages,Define Name-Space 從宣告package開(kāi)始到Block結(jié)束為package的範(fàn)圍 在一個(gè)packages中的variable為private(在package之外看不到) 要參用其他package的variable $packagevariable Example 26 The Standard Perl Library perl -e print “INCn” require(File_name): Include另一個(gè)Perl Script,Example 1,$ cat emp.first lgor Chevsky:6/23/83:W:59870
39、:25:35500:2005.50 Nancy Conrad:6/18/88:SE:23556:5:15000:2500 Jon Deloar:3/28/85:SW:39673:13:22500:12345.75 Archie Main:7/25/90:SW:39673:21:34500:34500.50 Betty Bumble:11/3/89:NE:04530:17:18200:1200.75 $ perl -ne print emp.first $ per -ne print if /Igor/ emp.first $ perl -ne print emp.temp,Example2,$
40、cat ex2.perl #!/usr/local/bin/perl # My First Perl Script print “Hello to you and yours!n”; $ perl -c ex2.perl ex2.perl syntax OK chmod +x ex2.perl ex2.perl Hello to you and yours!,Example 3,print “Hello”, “World”, “n”; print “Hello Worldn”; print Hello, World,”n”; print STDOUT Hello, World, “n”;,Ex
41、ample 4 - Print Literals,print “The price is $100.n”; print “The price is $100.n”; print “The price is $”, 100, “.n”; print “The number is “, 0777,”.n”; print “The number is “, 0 xAbcf ,”.n”; print “The unformatted number is “, 14.56 ,”.n”; print “*tIn double quotest*n”; print *tIn single quotest*n;
42、 print “attThe UnumberE LISE”,0777,”.n”;,Example 5 - Special Literals,print “We are on line number “, _LINE_,”.n”; print “The name of this file is “, _FILE_,”.n”; _END_ Ignored by the perl.,Example 6 - printf,printf “Hello to you and yours %s!n”, “Claven Ke”; printf(“%-15s%-20sn”,”Jack”, “Sprat”); p
43、rintf “The number in decimal is %dn”, 45; printf “The formatted number is I%10dIn”, 100; printf “The number printed with leading zeros is I%010dIn”,5; printf “Left justified the number is I%-10dIn”, 100; printf “The number in Octal is %on”, 15; printf “The number in Hex is %xn”, 15; printf “The form
44、atted floating point is I%8.2fIn”,14.3456; printf “The floating point is %8fn”, 15;,Example 7,#!/usr/local/bin/perl $salary=50000; months=(Mar,Apr,May); %states=(CA,California, ME,Maine, Mt,Montana, NM,New Mexico,); print “$salaryn”; print “monthsn”; print “$months0,$months1,$months2n”; print “$stat
45、esCA, $statesNMn”; print “%statesn”; print %states,”n”; print $x+3,”n”; print “*$name*n”;,Example 8,#!/usr/local/bin/perl $num=5; print “The number is $num.n”; print “I need $5.00.n”; print “ttI Cannot help you.n”; print I need $5.00., ”n”; print ttI Cant help you.n; print “The date is “, date; prin
46、t “The date is date”; $dir = pwd print “The current directory is $dir.n”;,Example 9 - Array,#!/usr/local/bin/perl names=(John,Joe,Jake); print names, “n”; print “Hi $names0,$names1, and $names2!n”; $number=names; print “There are $number elements in the names array.n”; print “The last element of the
47、 array is $names$number-1.n”; print “The last element of the array is $name$#namesn”; colors=(red,green,yellow,orange); ($c0,$c1,$c3,$c5)=colors; print “colorsn”; print $c0,”n”, $c1,”n”, $c2,”n”, $c3,”n”, $c4,”n”, $c5,”n”;,Example 10,#!/usr/local/bin/perl names=(“Bob”,”Dan”,”Tom”,”Guy”); push(names,
48、Jim,Joseph,Arch); print “names n”; $got=pop(names); print “names n”; print “The name got is $got.n”;,#!/usr/local/bin/perl names=(“Bob”,”Dan”,”Tom”,”Guy”); $got=shift(names); print “names n”; print “The name shifted is $got.n”; unshift(names,Jim,Joseph); print “names n”;,Example 11,#!/usr/local/bin/
49、perl $string=“Joe Blow:11/12/86:10 Main St.:Boston MA:025”; line=split(/:/ ,$string); print line, “n”; print “The guys name is $line0. n”; print “The birthday is $line1.nn”; str=split(/:/,$string,2); print $str0,”n”, $str1,”n”, $str2,”n”;,str=split(/:/,$string); print $str0,”n”, $str1,”n”, $str2,”n”
50、, $str3,”n”, $str4,”n”, $str5,”n” ; ($name,$birth,$address)=split(/:/,$string); print $name,”n”; print $birth,”n”; print $address,”n”;,Example 12,%weekday=(1,Monday,2,Tuesday,3,Wednesday,4,Thursday,5,Friday,6,Saturday,7,Sunday); foreach $key (keys(%weekday) print “$key “; print “n”; foreach $value (
51、 values(%weekday) print “$value “; print “n”;,%weekday=(1,Monday,2,Tuesday,3,Wednesday,4,Thursday,5,Friday,6,Saturday,7,Sunday); while ($key,$value)=each %weekday) print “$key = $valuen”; foreach $key (keys %weekday) delete $weekday$key; ,Example 13,$x=5; $y=4; $result = $x = $y; print $resultn; $re
52、sult = $x != $y; print $resultn; $result = $x $y; print $resultn; $result = $y $x; print $resultn;,$str1=A; $str2=B; $result = $str1 eq $str2; print $resultn; $result = $str1 ne $str2; print $resultn; $result = $str1 cmp $str2; print $resultn; $result = $str2 cmp $str1; print $resultn; $str1=B; $res
53、ult = $str1 cmp $str2; print $resultn;,Example 14,$line = Happy New Year; $x = kid; $y = nap; $z=*; print $z x 10, n; print $x . $y, n; print $z x 10, n; print ($x . $y. ) x 5); print n;,$line = Happy New Year; print substr($line,6,3),n; print index($line, Year),n; print substr($line, index($line,Ne
54、w),n; substr($line,0,0)=Fred, ; print $line,n; substr($line,0,1)=Ethel; print $line,n; substr($line,-1,1)=r to you!; print $line,n;,Example 15,$num1=1; $num2=0; $str1=Hello; $str2=; if ($num1) print True!n; $x+; if ($num2) print False!n; $y+; if ($str1) print True Again!n; if ($str2) print False Aga
55、in!n; print Not Equal!n if $x != $y;,Example 16,#!/usr/local/bin/perl print What version of the operating system are you using? ; chop ($os=); if ($os 2.2) print Most of the bugs have been worked out!n; else print Expect some problems.n; $hour=date +%H; if ($hour =0 ,Example 17,$str=Hello; numbers=(1,3,5,7,9); print The scalar $str is initially $str.n; print The array numbers is initially numbersn; foreach $str(numbers) $str += 5; print $strn; print Out of the loop - $str is str.n; print Out of the loop -
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025至2030年中國(guó)塑膠百葉窗簾零配件數(shù)據(jù)監(jiān)測(cè)研究報(bào)告
- 鎮(zhèn)江事業(yè)編面試題及答案
- 2025年軍隊(duì)文職人員招聘之軍隊(duì)文職管理學(xué)與服務(wù)題庫(kù)附答案(基礎(chǔ)題)
- 2025年軍隊(duì)文職人員招聘之軍隊(duì)文職管理學(xué)與服務(wù)題庫(kù)練習(xí)試卷A卷附答案
- 采購(gòu)交易基本合同范本
- 2024年四川省公務(wù)員《申論(行政)》試題真題及答案
- 高鐵乘客知識(shí)培訓(xùn)課件
- 年終慶典暨員工表彰大會(huì)方案
- 智能家居設(shè)備集成商服務(wù)協(xié)議
- 山西省呂梁市柳林縣2024-2025學(xué)年七年級(jí)上學(xué)期期末生物學(xué)試題(含答案)
- 旋挖樁施工工藝
- 綜評(píng)研究性學(xué)習(xí)及創(chuàng)新成果范例
- 全國(guó)商用密碼應(yīng)用優(yōu)秀案例匯編
- 點(diǎn)到表(標(biāo)準(zhǔn)模版)
- 護(hù)理安全警示教育ppt
- 老年人醫(yī)養(yǎng)結(jié)合服務(wù)記錄表單
- GB/T 4649-2018工業(yè)用乙二醇
- GB/T 26076-2010金屬薄板(帶)軸向力控制疲勞試驗(yàn)方法
- DSA室的手術(shù)配合教學(xué)課件
- 人教版四年級(jí)下冊(cè)音樂(lè)第四單元《凱皮拉的小火車(chē)》優(yōu)質(zhì)教案
- 三調(diào)土地利用現(xiàn)狀分類(lèi)和三大地類(lèi)對(duì)應(yīng)甄選
評(píng)論
0/150
提交評(píng)論