Perl Programmingprogramming
Total Page:16
File Type:pdf, Size:1020Kb
PerlPerl ProgrammingProgramming Get Your Jobs Done! Computer Center, CS,NCTU SlidesSlides ContentsContents Introduction File Handle Data Structure and Sorting Flow Control CPAN • Scalar Complex Data Structure • List, Array and Hash Reference Reading • More on variables Appendix Regular Expression Subroutine Basic I/O 2 IntroductionIntroduction Perl Poetry: study, write, study, do review (each word) if time. close book. sleep? what's that? From a graduate student (in finals week) Computer Center, CS,NCTU IntroductionIntroduction (1)(1) PERL • Practical Extraction and Report Language • PEARL was used by another language • Created by Larry Wall and first released in 1987 Useful in • Text manipulation • Web development • Network programming • GUI development • System Prototyping • …anything to replace C, shell, or whatever you like 4 Computer Center, CS,NCTU IntroductionIntroduction (2)(2) Compiled and interpreted • Efficient Syntax Sugar • die unless $a == $b; Object oriented Modules • CPAN Perl6 • http://dev.perl.org/perl6/ • Pugs – http://www.pugscode.org/ ¾/usr/ports/lang/pugs/ • Parrot – http://www.parrotcode.org/ 5 Computer Center, CS,NCTU IntroductionIntroduction--HelloHello WorldWorld (1)(1) Hello World! #!/usr/bin/perl -w # My First Perl Program print “Hello”, “ world!\n”; #!/usr/bin/perl -w • Write down the location of perl interpreter # My First Perl Program • Comment, to the end of line print(“Hello”, ” world!\n”); • Built-in function for output to STDOUT C-like “;” termination 6 Computer Center, CS,NCTU IntroductionIntroduction--HelloHello WorldWorld (2)(2) hello.pl $name = <STDIN>; #!/usr/bin/perl chomp $name; print “What is your name? ”; chomp($name = <STDIN>); chomp is not pass by value print(“Hello, $name!\n”); Value interpolation into string scalar variable = <STDIN> • Read ONE line from standard input chomp • Remove trailing “\n” if exists Variables are global unless otherwise stated Run Perl Program % perl hello.pl (even no +x mode or perl indicator) % ./hello.pl (Need +x mode and perl indicator) 7 ScalarScalar DataData 1 + 1 == 10 Computer Center, CS,NCTU ScalarScalar DataData (1)(1)--TypesTypes Use prefix ‘$’ in the variable name of a scalar data • $scalar_value Numerical literals • Perl manipulates numbers as double-decision float point values • Float / Integer constants, such as: ¾1.25, -6.8, 6.23e23, 12, -8, 0377, 0xff, 0b00101100 Strings • Sequence of characters • Single-Quoted Strings (No interpolation) ¾‘$a\n is printed as is’, ‘don\’t’ • Double-Quoted Strings (With interpolation) ¾“$a will be replaced by its value.\n” ¾Escape characters – \n, \t, \r, \f, \b, \a 9 Computer Center, CS,NCTU ScalarScalar DataData (2)(2)--AssignmentsAssignments Operators for assignment • Ordinary assignment ¾$a = 17 ¾$b = “abc” • Short-cut assignment operators ¾Number: +=, -=, *=, /=, %=, **= ¾String: .=, x= – $str .= “.dat” Î$str = $str . “.dat” • Auto-increment and auto-decrement ¾$a++, ++$a, $a--, --$a 10 Computer Center, CS,NCTU ScalarScalar DataData (3)(3)--OperatorsOperators Operators for Numbers • Arithmetic ¾+, -, *, /, %, ** • Logical comparison ¾<, <=, ==, >=, >, != Operators for Strings • Concatenation “.” ¾“Hello” . “ ” . “world!” Î “Hello world!” • Repetition “x” ¾“abc” x 4 Î “abcabcabcabc” • Comparison ¾lt, le, eq, ge, gt, ne man perlop 11 Computer Center, CS,NCTU ScalarScalar DataData (4)(4)--ConversionConversion Implicit conversion depending on the context • Number wanted? ( 3 + “15” ) ¾Automatically convert to equivalent numeric value ¾Trailing nonnumeric are ignored – “123.45abc” Î 123.45 • String wanted? ¾Automatically convert to equivalent string ¾“x” . (4 * 5) Δx20” 12 Computer Center, CS,NCTU ScalarScalar DataData (5)(5)--StringString RelatedRelated FunctionsFunctions Find a sub-string • index(original-str, sub-str [,start position]) index(“a very long string”, “long”); # 7 index(“a very long string”, “lame”); # -1 index(“hello world”, “o”, 5); # 7 index(“hello world”, “o”, 8); # -1 Sub-string • Substring(string, start, length) substring(“a very long string”, 3, 2); # “er” substring(“a very long string”, -3, 3); # “ing” Formatting data • sprintf (C-like sprintf) man perlfunc: Functions for SCALARs or strings 13 Computer Center, CS,NCTU BranchesBranches--ifif // unlessunless True and False • 0, “0”, “”, or undef are false, others are true • “00”, “0.00” are true, but 00, 0.00 are false if-elsif-else if( $state == 0 ) { statement_1; statement_2; …; statement_n } elsif( $state == 1 ) { statements; } else { statements; } unless: short cut for if (! ….) unless( $weather eq “rain” ) { if( ! $weather eq “rain” ) { go-home; go-home; } } print “Good-bye” if $gameOver; 14 Keep_shopping() unless $money == 0; Computer Center, CS,NCTU Relational Operators if ($a == 1 && $b == 2) {…} if ($a == 1 || $b == 2) {…} if ($a == 1 && (! $b == 2)){…} if (not ($a == 1 and $b == 2) or ($c == 3)) {…} • not > and > or || has higher precedence than or, = • $a = $ARGV[0] || 40; # if $ARGV[0] is false, then $a = 40 • $a = $ARGV[0] or 40; # $a = $ARGV[0] open XX, “file” or die “open file failure!”; • or can be used for statement short-cut. man perlop for precedence 15 List,List, Array,Array, andand HashHash Computer Center, CS,NCTU ListList Ordered scalars, similar to linked-list List literal • Comma-separated values • Ex: ¾(1, 2, 3, 4, 5,) ¾($a, 8, 9, “hello”) ¾($a, $b, $c) = (1, 2, 3) ¾($a, $b) = ($b, $a) Î swap List constructor • Ex: ¾(1 .. 5)Î(1,2,3,4,5) ¾(a .. z) Î(a,b,c,d,e,…,z) ¾(1.3 .. 3.1) Î(1,2,3) ¾($a .. $b) Îdepend on values of $a and $b 17 Computer Center, CS,NCTU ArrayArray (1)(1) An indexed list, for random access Use prefix ‘@’ in the variable name of an array • @ary = (“a”, “b”, “c”) • @ary = qw(a b c) • @ary2 = @ary • @ary3 = (4.5, @ary2, 6.7) Î (4.5, “a”, “b”, “c”, 6.7) • $count = @ary3 Î 5, scalar context returns the length of an array • $ary3[-1] Î The last element of @ary3 • $ary3[$#ary3] Î $#ary3 is the last index • ($d, @ary4) = ($a, $b, $c) Î $d = $a, @ary4 = ($b, $c) • ($e, @ary5) = @ary4 Î $e = $b, @ary5 = ($c) 18 Computer Center, CS,NCTU ArrayArray (2)(2) Slice of array • Still an array, use prefix ‘@’ • Ex: ¾@a[3] = (2) ¾@a[0,1] = (3, 5) ¾@a[1,2] = @a[0,1] Beyond the index • Access will get “undef” ¾@ary = (3, 4, 5) ¾$a = $ary[8] • Assignment will extend the array ¾@ary = (3, 4, 5) ¾$ary[5] = “hi”Î @ary = (3, 4, 5, undef, undef, “hi”) 19 Computer Center, CS,NCTU ArrayArray (3)(3) Interpolation by inserting whitespace • @ary = (“a”, “bb”, “ccc”, 1, 2, 3) • $all = “Now for @ary here!” ¾ “Now for a bb ccc 1 2 3 here!” • $all = “Now for @ary[2,3] here!” ¾ “Now for ccc 1 here!” Array context for file input • @ary = <STDIN> ¾Read multiple lines from STDIN, each element contains one line, until the end of file. • print @ary Î Print the whole elements of @ary 20 Computer Center, CS,NCTU ArrayArray (4)(4) List or array operations Initially, @a = (1, 2); • Push, pop and shift ¾Use array as a stack – push @a, 3, 4, 5 Î @a = (1, 2, 3, 4, 5) – $top = pop @a Î $top = 5, @a = (1, 2, 3, 4) ¾As a queue – $a = shift @a Î $a = 1, @a = (2, 3, 4) • Reverse list ¾Reverse the order of the elements – @a = reverse @a Î @a = (4, 3, 2) • Sort list ¾Sort elements as strings in ascending ASCII order – @a = (1, 2, 4, 8, 16, 32, 64) – @a = sort @a Î (1, 16, 2, 32, 4, 64, 8) • Join list – @a=(1,2,3); $b = join ":", @a Î $b = “1:2:3” 21 Computer Center, CS,NCTU HashHash (1)(1) Collation of scalar data • An array whose elements are in <key, value> orders • Key is a string index, value is any scalar data • Use prefix “%” in the variable name of a hash • Ex: ¾ %age = (john => 20, mary => 30, ); Î same as (“john”, 20, “mary”, 30) ¾ $age{john} = 21; Î “john” => 21 ¾ %age = qw(john 20 mary 30) ¾ print “$age{john} \n” 22 Computer Center, CS,NCTU HashHash (2)(2) Hash operations %age = (john => 20, mary => 30, ); • keys ¾Yield a list of all current keys in hash – keys %age Î (“john”, “mary”) • values ¾Yield a list of all current values in hash – values %age Î (20, 30) • each ¾Return key-value pair until all elements have been accessed – each(%age) Î (“john”, 20) – each(%age) Î (“mary”, 30) • delete ¾Remove hash element – delete $age{“john”} Î %age = (mary => 30) 23 Computer Center, CS,NCTU FlowFlow ControlControl --whilewhile // untiluntil while and do-while $a = 10; while ( $a ) { print “$a\n”; --$a } $a = 10; print “$a\n” and --$a while $a ; do { statements-of-true-part; } while (condition); until and do-until • until (…) == while (! …) $a = 10; until ($a == 0) { print “$a\n”; --$a } do { statements-of-false-part; } until (expression); 24 Computer Center, CS,NCTU FlowFlow ControlControl --forfor // foreachforeach for @a = (1, 2, 3, 4, 5) for (my $i = 0; $i <= $#a; ++$i) { print “$a[$i]\n”; } foreach • For example: %age = (john => 20, mary => 30, ); foreach $name (keys %age) { print “$name is $age{$name} years old.\n”; } for (keys %age) { print “$_ is $age{$_} years old.\n”; } 25 Computer Center, CS,NCTU FlowFlow ControlControl --last,last, next,next, redoredo Loop-control • last ¾Like C “break” • next ¾Like C “continue” • redo ¾Jump to the beginning of the current loop block without revaluating the control expression ¾Ex: for($i=0;$i<10;$i++) { # infinite loop if($i == 1) { redo; } } 26 Computer Center, CS,NCTU FlowFlow ControlControl --LabeledLabeled BlockBlock Give name to block to archive “goto” purpose Use last, next, redo to goto any labeled block 1 1 1 1 1 2 Example: 1 1 3 1 2 1 LAB1: for($i=1;$i<=3;$i++) { 1 2 2 LAB2: for($j=1;$j<=3;$j++) { 1 2 3 LAB3: for($k=1;$k<=3;$k++)