Perl使用介绍.ppt_第1页
Perl使用介绍.ppt_第2页
Perl使用介绍.ppt_第3页
Perl使用介绍.ppt_第4页
Perl使用介绍.ppt_第5页
已阅读5页,还剩78页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

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執行Perl $ perl -e print “hello dollyn”; The -n Switch:對檔案的每一行執行相同的動作 Example 1 The -c Switch: 檢查Script的語法 $ 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)與報告(report format)需要先宣告 Variable不需先宣告 Initialize 為 0 或 空字串 (),The Script,Startup: Script 的第一行寫上 #! #!/usr/local/bin/perl Comments: # Sample Script: ex2.perl 如果第一行沒加上 #! ? 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,大小寫不同(case sensitive) Quotes 單引號:不做任何變數或特殊字元的轉換 雙引號 $, $, , %,常數(Literal, Constant),數值常數 12345 0

5、 x456fff (16進位) 0777(8進位) 23.45 .234E-2 字串常數 t n r f b a e 033 xff l u L U E ,常數(Cont.),特殊常數 _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 會換成該有的值 Associative array 不會換 t, n, 等一定要包在 “” 內 : 不會做任何轉換 : 執行包在裡頭的指令,Scalar Variables,變數名稱前要加 $ $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),變數名稱前要加 student 要存取Array中的單一元素要用 $ $student4 Array的第一個元素Index為0 Array中的元素可以是數

10、值與字串的混合,name = (“Guy”,”Tom”,”Dan”); grades=(100,90,65,96,40,75); items=($a,$b,$c) empty=(); $size=items;,Array (II),$#arrayname = 最後一個元素的Index $ = 第一個元素的Index(0) Array可以隨時增加或減少裡頭的元素 Example 9,$indexsize=$#grades; $#grades=3; $#grades=$ - 1 $grades=(); digits=(0.10); letters=(A.Z);,Associative Arrays

11、,變數名前要加 % 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 = 砍掉字串的最後一個字元 #!/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接起來,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 會依狀況作變數型態的轉換,#!/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接起來

26、$str1.$str2 將 $str1重複$num times $str1 x $num 將 $str1 自 $offset 起取 $len 個字元 substr($str1,$offset,$len) 看$str2在$str1中出現的地方 index($str1,$str2) EXPR的長度 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裡頭的指令會重複執行 通常Block中會含有在某時候把 (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裡頭的指令會重複執行 通常Block中會含有在某時候把 (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、類似 while/until Loop, 但是Block內的指令至少會執行一次,$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中每一個element的值給Variable後執行Bl

31、ock指令 Variable的值在執行完 foreach之後回復為原有的值(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第一次出現的 abc hhhabczzzabckkkabc,The m Operator,用來尋找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: 只取代每一行的第一個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中用的變數. 出了subroutine後就不見了 local(local_var1, local_var2,) Example 24 Return Value:subroutine最後一個Expression的值 Example

38、25,Packages,Define Name-Space 從宣告package開始到Block結束為package的範圍 在一個packages中的variable為private(在package之外看不到) 要參用其他package的variable $packagevariable Example 26 The Standard Perl Library perl -e print “INCn” require(File_name): Include另一個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. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论