Perl语言入门和提高02

Perl语言入门和提高02

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Spring, 2009 Spring, 2009 Precedence Level Level Left to right -> Infix dereference Operator Left to right ++, -- Auto increment, Auto decrement None 19 ** Exponentiation Right to left 18 !, ~, +,+, -,\ Logical not, bitwise not, unary plus, unary minus, reference Right to left 17 =~, !~ Match, Not match Left to right 16 *, /, % x Multiply, Divide, Modulus, Repetition Left to right 15 +, -,. Add, Subtract, String concatenation Left to right 14 <<,>> Bitwise left shift, Bitwise right shift Left to right 13 File test Operators None 12 Relational Operators None 11 周晓方 [email protected] Associativity Function Calls, Parentheses, Array subscripts 20 Lesson 2 Description (), , {} 21 Perl 入门和提高 Operator 22 Equality Operators None 10 & Bitwise and Left to right 9 |, ^ Bitwise or, Bitwise xor Left to right 1 5 Spring, 2009 How to get help? 获得帮助 Spring, 2009 Precedence (cont.) 8 && Logical and Left to right 7 || Logical or Left to right 6 .. Range Operator None 5 • All the viewgraphs and books • On-line documents (Windows) ?: Ternary or conditional Operator Right to left AssignmentOperators Right to left Comma Operator Left to right 4 – C:/perl/html/index.htm – Click perlfunc, perlfaq, perlxs, …… 3 , 2 not Low precedence logical Operators Left to right 1 and Low precedence logical Operators Left to right 0 or, xor Low precedence logical Operators Left to right • 逐渐习惯Perl的写法 • perldoc command – if (($a > 4) && ($b > 6)) {…;} if ($a > 4 and $b > 6) {…;} – if (not open F, "a.txt") { die; } die if not open $, "a.txt"; open F, "a.txt" or die; – if ($a < 0) { $a = -$a;} – perldoc -f print – perldoc -m benchmark – perldoc perldoc perldoc perlfunc – perldoc perlop查看perl关于运算符的文档 – Sometimes use with "pod2text", "pod2html" $a >= 0 or $a = -$a; 6 2 关联数组 Hash --% Spring, 2009 Context上下文: scalar, list • Index (or key) is an scalar (usually a string, not only numbers). • Order-less. • Relational database @junk print print $size $size q q q q q Spring, 2009 = (1, "I", undef, 66..69, "foo"); @junk; #array context 1I66676869foo @junk . "\n"; #scalar context 8 = @junk; #scalar context $size is 8 = scalar @junk; $size is 8 #scalar() force a scalar context scalar @array returns number of elements scalar (LIST) returns its final element These are scalar context print @junk . “\n”; print @junk + 0; $size = @junk; These are list context print @junk, “\n”; ($head) = @junk; Function behaviors differently to context $line = <FILE>; @lines = <FILE>; %assoArr = ("Jack", "Dec 2", "Joe", "June 2", "Jane", "Feb 13"); %assoArr = ("Jack"=>"Dec 2", "Joe"=>"June 2", "Jane"=>"Feb 13"); $assoArr{"Marry"} = "Oct 10"; 多数情况下,key串的引号可省略 $assoArr{"Jennifer"} = "Mar 20"; print "Joe's birthday is: " . $assoArr{Joe} . "\n"; =>Joe's birthday is: June 2 %assoArr = (); #empty hash. %hex2bin = (0 => "0000", 1 => "0001", ... , F=>"1111"); $hex = "A19e"; $bin = join("_",map($hex2bin{$_}, split(//,uc $hex))); =>1010_0001_1001_1110 3 7 Spring, 2009 Spring, 2009 Operators, See also "perlop" Functions working with HASH, 1 • • • • • • • • • • Binary op: + - * **(exponentiation) / %(Modulus) Unary op: +var -var ++var --var var++ var-Logical op: && || ! and or not xor Bitwise op: & | ^ >> << ~ Numeric relation: == != < <= > >= <=> String relation: eq ne lt le gt ge cmp Ternary op: a ? b : c Range op: (1..5, "A".."D") String op: . x Assign: = += -= *= /= %= .= **= x= <<= >>= &= &&= |= ||= ^= • Other: () {} \(referenct) ->(infix dereference) • Nevery call print %hash; since hash is orderless. • @key = sort keys %hash – foreach $key (sort keys %hash) {print $hash{$key};} • @key = keys %hash; @value = values %hash; • ($key, $val) = each(%hash) # less memory use each( ) returns once a pair, returns undef at last. 历遍哈希表 print "$key=$value\n" 环境变量在hash%ENV中 while (($key,$value) = each %ENV); # never modify %hash inside the while each loop!!! TZ=BJT-8 PROCESSOR_REVISION=0806 NUMBER_OF_PROCESSORS=1 USERPROFILE=C:\WINNT\Profiles\xfzhou TMPDIR=c:/temp COMPUTERNAME=N30 ... Printed with FinePrint 2000 - purchase at http://www.fineprint.com 4 8 Spring, 2009 Spring, 2009 More on RE Rule 1 Functions working with HASH, 2 • Quantifiers: * (any times, even 0), + (1 or more), ? (none or once) 例如 $line =~ s/ +/ /g; 合并相邻的空格 • Remove one hash from hash table – 删除单个元素: delete $hash{$key};# remove whole pair – This is wrong: undef $hash {key}; #key still exists – 删除hash片断: delete @hash{key1, key2, key3 …}; • Quantifiers: {n} n times, {n,} n or more, {n1, n2} n1 to n2 times • greedy (+, *) or lazy (+?, *?) 贪婪和懒惰,实例: • Delete a whole hash table $a = "zzzzzzzzzzzzzzzzzfaaaadcccccdtttdeee" $a =~ /f.*d/ #matches faaaadcccccdtttd $a =~ /f.*?d/ #matches faaaad – %hash = (); – undef %hash; • Check existence of a hash • • • • – if (exists $hash{$key}) {….} – This is wrong: if ($hash{$key}) {….} 值可能是0或undef – This is also wrong: if (defined $hash{$key}) … • delete和exists函数也可以用于普通数组 ( ): group and pattern memory Words \w [a-zA-Z0-9_], Spaces \s [\t \n], Digits \d [0-9], \W \S \D [^a-zA-Z0-9_] [^\t \n] [^0-9] • \b, word boundary (zero width) \B, non-word boundary – 和splice( )不同,delete( ) 后,下标不变,exists( )为假 – 只有delete了数组的最后一个元素,数组才会缩小。 9 Reference to hash table • Reference: \ $Rhash = \%hash; 13 Spring, 2009 Dereference: % More Samples Spring, 2009 /0|[1-9][0-9]*/ 匹配自然数 /\$[a-z][a-z0-9_]*/i 匹配普通scalar名称 /\bcat\b/ 匹配cat,但不匹配catch /^$/ 匹配空行 s/#.*// 删除注释部分 • 带修饰g和e的RE,带反向引用的RE s/\d+/0/g 全部数字串变'0' s/(\d+)/ $1 /g 全部数字前后加空格 s/(\d+)/$1+1/ge 全部数字串加1 • 留心元字符、$和@, RE是带插值功能的 /my\@school\.com/ [email protected] [email protected] 同上(无插值无meta) m!my\@school\.com! 同上(先插值后meta) %{$Rhash} is a hash • Refer to anonymous hash $Rh = { 'dog'=>'bark', 'cat'=>'mew', }; print "Sound of dog is ${$Rh}{dog} \n"; • Short hands 省略{}、写成->的样子 – ${$a} ≡ $$a, @{$a} ≡ @$a, %{$a} ≡ %$a, etc – Ref to list: $a = [1, 2, 3, "AAB"] ${$a}[0]=50; $$a[0]=50; $a->[0]=50; # same – Ref to hash:$h= {cat=>"rat", dog=>"meat"} ${$h}{rat}="rice"; $$h{rat}="meat"; print $h->{rat}; – 注意优先级,perl的$$a[j]和C语言的*x[j]不同 $$a[j]和${$a[j]}不同 10 14 Spring, 2009 Spring, 2009 Regular expression--Rule 2 Try some Regular Expressions • 看文档: perlre perlretut perlop • Match: //, m// $catstring =~ /cat/; # interpolation & meta • Substitute: s/// $a =~ s/([0-9]+)/$1+1/ge; #interpolation & meta in match, interpolation (but no meta) in replacement • Translate: tr/// $a =~ tr/A-Z/a-z/; # no interpolation! $a = 'dog catches cats.'; print $a =~ /cat/ ? 'Y ' : 'N '; # Match print $a =~ /^cat/ ? 'Y ' : 'N '; $a =~ s/cat|dog/pet/g; # Substitute print "\n$a\n"; $a =~ tr/a-z/za-y/; # Translate print "$a\n"; – $result !~ tr/0-9/a-j/; # translate 0-9 to a-j, and return false if happened. • Delimiters – m.cat., m/\/usr\//, m{/usr/}, m!/usr/! – m/$file/ (interplation and meta), m'$file' (neither interplation nor meta) – s{bbb}{12345}; s/bbb/12345/ Results: YN pet petches pets. ods odsbgdr odsr. • (Default var is $_) Binding operator: =~ or !~, !~ for not match • Only works on scalar. WRONG: @arrayName =~ m/pattern/; =~ pattern/ • Only matches the left most. Only mathes once (by default) most. default) 15 11 RE Rule 1:通配符,元字符 Spring, 2009 Spring, 2009 • Literal: m/a/, m/\$/, m/AbCd/ • ^ caret: Begin of a str/line: m/^#/ -- a line begin with pond sign • $ dollar: End of a str/line: s/$/##/m -- append “##” to each line • | (verital bar) alternation: s/dog|cat/pet/g -- all dog or cat to pet • . dot: any char except new line (except ///s): m/./ non-empty string • Char-set with meta-char “-” and “^”, e.g. [A-Z] [a-z0-9] [+\-] [^0-9] • \ escape char : e.g. match for “/usr/”: $path =~ /\/usr\// RE Rule 3: 处理插值和通配符 • Interplation 1st, than processing meta chars – – – – – A very strong but not easy to debug feature. $a="cat|dog"; $b =~ /$a/; # match cat or dog @a=("cat", "dog"); $" = "|"; $b=~ [email protected]/; $a="/usr/"; $b =~ /$a/; #得到//usr// WRONG Solution: 1. Escape $a: $a= '\/usr\/'; # not "\/usr\/" !! 2. Change delimiters: $b=~ m[$a]; 3. Calling quotemeta( ): $a = quotemeta("/usr/"); • Exception: – tr/// is always built in compile time. Printed with FinePrint 2000 - purchase at http://www.fineprint.com 12 16 ...
View Full Document

This note was uploaded on 11/27/2011 for the course CS Perl taught by Professor Guo during the Spring '09 term at Xiamen University.

Ask a homework question - tutors are online