PerlPerl ProgrammingProgramming

Get Your Jobs Done! File Handle Sorting CPAN Complex Data Structure Reference Reading Appendix ‰ ‰ ‰ ‰ ‰ ‰ Scalar List, Array and Hash More on variables • • • Introduction Data Structure and Flow Control Regular Expression Subroutine Basic I/O Slides Contents ‰ ‰ ‰ ‰ ‰ Slides Contents

Computer Center, CS, NCTU 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) and first released in 1987 Practical Extraction and Report Language language PEARL was used by another Created by Text manipulation Web development Network programming GUI development System Prototyping …anything to replace C, shell, or whatever you like • • • • • • • • • Useful in Introduction (1) ‰ ‰ Introduction (1)

Computer Center, CS, NCTU 4 http://www.parrotcode.org/ http://www.pugscode.org/ /usr/ports/lang/pugs/ ¾ Efficient die unless $a == $b; CPAN http://dev.perl.org/perl6/ Pugs – Parrot – • • • • • • Compiled and interpreted Syntax Sugar Object oriented Modules Perl6 Introduction (2) ‰ ‰ ‰ ‰ ‰ Introduction (2)

Computer Center, CS, NCTU 5 Hello World (1) Hello World (1) - - ” termination ; Write down the location of perl Write down the location of perl Comment, to the end of line Built-in function for output to STDOUT #!/usr/bin/perl -w # My First Perl Program print “Hello”, “ world!\n”; #!/usr/bin/perl -w # My First Perl Program print(“Hello”,world!\n”); ” • • • Hello World! C-like “ Introduction ‰ ‰ ‰ ‰ ‰ Introduction

Computer Center, CS, NCTU 6 de and perl indicator) Value interpolation into string $name = ; chomp $name; chomp is not pass by value mode or perl indicator) mode or perl ); (Need +x mo Hello World (2) Hello World (2) = - - line from standard input ONE Read if exists Remove trailing “\n” print(“Hello, $name!\n”); #!/usr/bin/perl print “What is your name? ”; chomp($name % perl hello.pl +x (even no % ./hello.pl • • hello.pl scalar variable = chomp Variables are global unless otherwise stated Run Perl Program Introduction ‰ ‰ ‰ ‰ ‰ Introduction

Computer Center, CS, NCTU 7 ScalarScalar DataData

1 + 1 == 10 t’ \’ uble-decision float point values Types Types - - \n, \t, \r, \f, \b, \a – 1.25, -6.8, 6.23e23, 12, -8, 0377, 0xff, 0b00101100 ‘$a\n is printed as is’, ‘don “$a will be replaced by its value.\n” Escape characters ¾ ¾ ¾ ¾ Float / Integer constants, such as: Float / Integer constants, Perl manipulates numbers as do Sequence of characters Single-Quoted Strings (No interpolation) Strings (With interpolation) Double-Quoted $scalar_value • • • • • • Use prefix ‘$’ in the variable name of a scalar data Numerical literals Strings Scalar Data (1) ‰ ‰ ‰ Scalar Data (1)

Computer Center, CS, NCTU 9 Assignments Assignments Î $str = $str . “.dat” - - $str .= “.dat” – $a = 17 $b = “abc” Number:String: -=, *=, /=, %=, **= +=, .=, x= $a++, ++$a, $a--, --$a ¾ ¾ ¾ ¾ ¾ Ordinary assignment Short-cut assignment operators Auto-increment and auto-decrement • • • Operators for assignment Scalar Data (2) ‰ Scalar Data (2)

Computer Center, CS, NCTU 10 “Hello world!” Î “abcabcabcabc” Operators Operators Î - - +, -, *, /, %, ** <, <=, ==, >=, >, != “Hello” . “ ” . “world!” “abc” x 4 lt, le, eq, ge, gt, ne ¾ ¾ ¾ ¾ ¾ Arithmetic Logical comparison Concatenation “.” “x” Repetition Comparison • • • • • Operators for Numbers Operators for Strings man perlop Scalar Data (3) ‰ Scalar Data (3) ‰ ‰

Computer Center, CS, NCTU 11 Conversion Conversion 123.45 Î Î ”x20” - - “123.45abc” – Automatically convert to equivalent numeric value Trailing nonnumeric are ignored Automatically convert to equivalent string “x” . (4 * 5) ¾ ¾ ¾ ¾ Number wanted? ( 3 + “15” ) Number wanted? ( 3 + “15” String wanted? • • Implicit conversion depending on the context Scalar Data (4) ‰ Scalar Data (4)

Computer Center, CS, NCTU 12 # 7 # -1 String Related Functions String Related Functions - - index(original-str, sub-str [,start position]) index(original-str, sub-str Substring(string, start, length) (C-like sprintf) sprintf • • • index(“avery long string”, “long”); index(“avery long string”, “lame”); # 7 index(“hello world”, “o”, 5); # -1 substring(“a very long string”, 3, 2); substring(“a very long string”, -3, 3); # “er” # “ing” index(“hello world”, “o”, 8); Find a sub-string Sub-string Formatting data man perlfunc: Functions for SCALARs or strings Scalar Data (5) ‰ ‰ ‰ ‰ Scalar Data (5)

Computer Center, CS, NCTU 13 { go-home; if( ! $weather eq “rain”if( ! $weather eq ) } t_2; …; statement_n { { if / unless if / unless - - statement_1; statemen statements; statements; { go-home; 0, “0”, “”, or undef are false, others true are true, but 00, 0.00 false “00”, “0.00” elsif( $state == 1 ) { else • • if( $state == 0 ) } } } print “Good-bye” if $gameOver; Keep_shopping() unless $money == 0; True and False if-elsif-else unless: short cut for if (! ….) unless( $weather eq “rain”unless( $weather eq ) } Branches ‰ ‰ ‰ ‰ ‰ Branches

Computer Center, CS, NCTU 14 = , or or ($c == 3)) {…} $b == 2) die “open file failure!”; ! $b == 2)){…} or and $b == 2) {…} $b == 2) {…} && || ($a == 1 can be used for statement short-cut. or not > and or $a = $ARGV[0] || 40; # if is false, then 40 $a = $ARGV[0] or 40; # not has higher precedence than • • • • || if ($a == 1 if ($a == 1 && ( open XX, “file” man perlop for precedence if ($a == 1 if ( Relational Operators ‰ ‰ ‰ ‰ ‰ ‰ ‰

Computer Center, CS, NCTU 15 List,List, Array,Array, andand HashHash swap Î (1,2,3) depend on values of $a and $b Î Î ,) 5 (a,b,c,d,e,…,z) , (1,2,3,4,5) , 4 Î Î 3 , 5) 2 .. , ( 1 (1 ($a, 8, 9, “hello”) $c) = (1, 2, 3) ($a, $b, ($a, $b) = ($b, $a) (a .. z) (1.3 .. 3.1) ($a .. $b) ¾ ¾ ¾ ¾ ¾ ¾ ¾ ¾ Comma-separated values Ex: Ex: • • • List constructor Ordered scalars, similar to linked-list List literal List ‰ ‰ ‰ List

Computer Center, CS, NCTU 17 The last element of @ary3 (4.5, “a”, “b”, “c”, 6.7) 5, scalar context returns the length of $#ary3 is the last index $d = $a, @ary4 ($b, $c) $e = $b, @ary5 ($c) an array Î Î Î Î Î Î (a b c) qw @ary = (“a”, “b”, “c”) @ary = @ary2 = @ary 6.7) @ary3 = (4.5, @ary2, $count = @ary3 $ary3[-1] $ary3[$#ary3] ($d, @ary4) = ($a, $b, $c) ($e, @ary5) = @ary4 • • • • • • • • • An indexed list, for random access Use prefix ‘@’ in the variable name of an array Array (1) ‰ ‰ Array (1)

Computer Center, CS, NCTU 18 @ary = (3, 4, 5, undef, “hi”) Î @a[3] = (2) @a[0,1] = (3, 5) @a[1,2] = @a[0,1] @ary = (3, 4, 5) $a = $ary[8] @ary = (3, 4, 5) $ary[5] = “hi” (2) (2) ¾ ¾ ¾ ¾ ¾ ¾ ¾ Still an array, use prefix ‘@’ Ex: Access will get “undef” Assignment will extend the array • • • • Slice of array Beyond the index Array ‰ ‰ Array

Computer Center, CS, NCTU 19 each element contains one line, Print the whole elements of @ary Î “Now for a bb ccc 1 2 3 here!” “Now for ccc 1 here!” Read multiple lines from STDIN, until the end of file. ¾ ¾ ¾ @ary = (“a”, “bb”, “ccc”, 1, 2, 3) here!” $all = “Now for @ary $all = “Now for @ary[2,3] here!” @ary = print @ary • • • • • Array context for file input Interpolation by inserting whitespace Array (3) ‰ ‰ Array (3)

Computer Center, CS, NCTU 20 @a = (4, 3, 2) @a = (1, 2, 3, 4, 5) $top = 5, @a (1, 2, 3, 4) $a = 1, @a (2, 3, 4) (1, 16, 2, 32, 4, 64, 8) $b = “1:2:3” Initially, @a = (1, 2); Initially, Î Î Î Î Î Î @a=(1,2,3); $b = join ":", @a push @a, 3, 4, 5 $a = shift @a @a = reverse @a = (1, 2, 4, 8, 16, 32, 64) @a = sort $top = pop @a – – – – – – – As a queue Use array as a stack Reverse the order of elements Sort elements as strings in ascending ASCII order ¾ ¾ ¾ ¾ Push, pop and shift Reverse list Sort list Join list • • • • List or array operations Array (4) ‰ Array (4)

Computer Center, CS, NCTU 21 same as (“john”, 20, “mary”, 30) “john” => 21 Î $age{john} = 21; %age = qw(john 20 mary 30) print “$age{john} \n” %age = (john => 20, mary => 30, ); Î ¾ ¾ ¾ ¾ An array whose elements are in orders Key is a string index, value any scalar data Use prefix “%” in the variable name of a hash Ex: • • • • Collation of scalar data Hash (1) ‰ Hash (1)

Computer Center, CS, NCTU 22 (“john”, “mary”) (20, 30) (“john”, 20) 30) (“mary”, %age = (mary => 30) Î Î Î Î Î %age = (john => 20, mary => 30, ); keys %age values %age each(%age) each(%age) delete $age{“john”} – – – – – Yield a list of all current keys in hash Yield a list of all current values in hash Return key-value pair until all elements have been accessed Remove hash element ¾ ¾ ¾ ¾ keys values each delete • • • • Hash operations Hash (2) ‰ Hash (2)

Computer Center, CS, NCTU 23 } print “$a\n”; --$a --$a { print “$a\n”; while / until while / until - - statements-of-false-part; statements-of-true-part; until (…) == while (! …) $a = 10; while ( $a ) --$a } ($a == 0) { print “$a\n”; $a = 10; until do { } until (expression); • $a = 10; printand “$a\n” --$a while $a ; do { } while (condition); while and do-while until and do-until Flow Control ‰ ‰ Flow Control

Computer Center, CS, NCTU 24 foreach foreach @a = (1, 2, 3, 4, 5) %age = (john => 20, mary => 30, ); for / for / - - is $age{$_} years old.\n”; $_ print “ $i = 0; <= $#a; ++$i) { print “$a[$i]\n”; print “$name is $age{$name} years old.\n”; my For example: for ( } $name (keys %age) { foreach } • for (keys %age) { } for foreach Flow Control ‰ ‰ Flow Control

Computer Center, CS, NCTU 25 last, next, redo last, next, redo - - redo; if($i == 1) { } Like C “break” Like C “continue” Jump to the beginning of current loop block Ex: without revaluating the control expression ¾ ¾ ¾ ¾ last next redo for($i=0;$i<10;$i++) { # infinite loop } • • • Loop-control Flow Control ‰ Flow Control

Computer Center, CS, NCTU 26 1 1 2 1 3 1 2 1 2 1 2 3 2 1 2 1 2 1 3 2 1 2 2 3 2 3 1 3 1 3 1 2 3 2 1 … Labeled Block Labeled Block - - print “$i $j $k\n”; print if(($i==1)&&($j==2)&&($k==3)) {last LAB2;} if(($i==2)&&($j==3)&&($k==1)) {next LAB1;} if(($i==3)&&($j==2)&&($k==1)) {next LAB2;} LAB3: for($k=1;$k<=3;$k++) { } Give name to block archive “goto” purpose Use last, next, redo to goto any labeled block Example: LAB2: for($j=1;$j<=3;$j++) { } LAB1: for($i=1;$i<=3;$i++) { } Flow Control ‰ ‰ ‰ Flow Control

Computer Center, CS, NCTU 27 MoreMore onon VariablesVariables undef undef - - $a = undef @ary = empty list () %h has no pairs Î Î Î ) {…} defined $var $a = undef $ary[2] = undef $h{“aaa”} = undef convert to 0 in numeric, or empty string “” is in string undef $a undef if ( undef @ary %h undef • • • • • • • • Scalar data can be set to undef You can do undef on variables Test whether a variable is defined More on Variables (1) ‰ ‰ ‰ More on Variables (1)

Computer Center, CS, NCTU 29 use strict use strict - - #to declaration Use ‘my’ option to enable warnings Need variable declaration, prevent from typo Also prevent from typo, skip the details. Reference type (skip) ¾ ¾ ¾ –w use strict vars strict use subs strict use refs strict use Variables without initialized occur warnings use vars qw($y) # Use ‘use vars’ to declaration use strict; my ($x); • • • • use strict contains “no strict” close the function to Use More on Variables (2) ‰ ‰ ‰ More on Variables (2)

Computer Center, CS, NCTU 30 ) ) Basic I/O ) Appendix 1st argument in $ARGV[0] ) ) corresponding to the errno file handler names Î subroutines default input and pattern-searching space output field separator for print input record separator (default: newline) pid uid program name (like $0 in shell-script) signal handlers for signals ( Appendix Current environment variables ( euid parameter list ( errno, or the error string current filename when reading from <> ( command line arguments ( command Î Î Î Î Î Î Î Î Î Î Î Î Î $_ $, $/ $$ $< $0 $> $! %SIG %ENV $ARGV @ARGV @_ STDIN, STDOUT, STDERR • • • • • • • • • • • • • • Predefined variables Predefined variables ‰ Predefined variables

Computer Center, CS, NCTU 31 BasicBasic I/OI/O ining lines as a list, end by EOF fied on the command line Input Input - - # process $line # process $_ Including array and hash $ARGV records the current filename @ARGV shifts left to remove the current filename ¾ ¾ ¾ In scalar context, return the next line or undef In list context, return all rema Get data from files speci Otherwise read from STDIN while( $line = ) { while( $line = ) } while() { } • • • • Using Using diamond operator <> Basic I/O (1) ‰ Basic I/O (1) ‰

Computer Center, CS, NCTU 33 Output Output - - print(“hello”, $abc, “world\n”); print “hello”, $abc, “world\n”; world\n”; print “hello $abc printf “%15s, %5d, %20.2f”, $name, $int, $float; – – – – Ex: Ex: ¾ ¾ Take a list of strings and send each string to STDOUT in turn A list of strings are separated by whitespace C-like printf • • • print LIST Using printf Basic I/O (2) ‰ ‰ Basic I/O (2)

Computer Center, CS, NCTU 34 RegularRegular ExpressionExpression

String pattern matching & substitution = “girl” 4 = “boy” , R , = “boy” 3 of the following set strings? goodbad girl, goodbadbad boy, …} goodbadbad goodbad girl, = “bad” , R = “bad” , 2 ) gives {good boy, good girl, bad boy, bad girl} boy, good girl, bad ) gives {good 6 R gives {good, bad} gives {good, girl} gives {boy, . ) ) as many times as you want, including 0 times as many times 2 4 5 R R x R = “good”, R or or 1 =( * gives {good, bad, goodgood, goodbad, badgood, badbad, …} 1 3 7 5 R R R R are regular expressions, so the following = =( =( 5 6 8 y ) Î R R R y ) y – – – or R . R * ) : repeat R x x x and R x {good boy, good girl, bad boy, {good boy, good girl, Basic regex: R What is the common characteristic What is the common characteristic (R (R (R • • • • • • String pattern If R Our final pattern is: (“good” or “bad”)* . (“boy” or “girl”) Regular expressions can be recognized very efficiently Regular Expression ‰ ‰ ‰ ‰ Regular Expression

Computer Center, CS, NCTU 36 [^a-zA-Z0-9_] [^0-9] [^ \r\t\n\f] Î Î \D Î \D tring of $string matches [a-zA-Z0-9_] \W [0-9] [ \r\t\n\f] \S character Î Î \d Î \w \s – – – single digit word whitespace , /[abc]/, /[0-9]/, /[a-zA-Z0-9]/, /[^0-9]/, /[abc\]]/ , /[abc]/, /[0-9]/, /[a-zA-Z0-9]/, /[^0-9]/, /./ ¾ ¾ ¾ /^hello$/ will match the entire string if (/xxxxx/) {…} matches $_ Return true if any subs /a/, Predefined character class abbreviations Predefined • • • • • if ($string =~ /(good|bad)*(boy|girl)/) {…} Match Regular Expression in Perl (1) ‰ ‰ Regular Expression in Perl (1)

Computer Center, CS, NCTU 37 m ~ n times, inclusive {0,} >=m times. =m times. {0,1} {1,} Î Î Î Î Î Î {m,n} * ? + {m,} {m} ¾ ¾ ¾ ¾ ¾ ¾ Multipliers /fo+ba?r/ /a.{5}b/ # f, one or more o, b, optional a, r char, b non-newline # a, any five • Match more than one character Regular Expression in Perl (2) ‰ Regular Expression in Perl (2)

Computer Center, CS, NCTU 38 # $1 = “this”, $2 = “is” # $1 = “this”, /a(.*)b\1c/ # match aXYbXYc or abc, but not aXbc ¾ $_ = “this is a test”; /(\w+)\W+(\w+)/; # match first two words, print “$1, $2\n”; Besides matching, also remember the matched string for future Besides matching, also remember the matched string reference \1 refer to 1st grouping, \2 for 2nd, … Ex: The same value as \1, \2, \3, but can be used outside /xxx/ Ex: • • • • • Grouping sub-regex by (…) $1, $2, $3, … Regular Expression in Perl (3) ‰ Regular Expression in Perl (3) ‰

Computer Center, CS, NCTU 39 # $` = “this is a ” # $` = “this # $& = “sample” string” = “ # $’ $_ = “this is a sample string”; /sa.*le/; Store before-matched, matched, after-matched strings Ex: • • $`, $&, $’ Regular Expression in Perl (4) ‰ Regular Expression in Perl (4)

Computer Center, CS, NCTU 40

- - # $_ = “bart barl barl # $_ = “bart bufbarn” # $sc = “ ” # $sc = “ # $war3 = “peace peace peace” $_ = “foot fool buffoon”; s/foo/bar/g; $sc = “this is a test”; $sc =~ s/(\w+)/<$1>/g; $war3 = “WAR War war”; $war3 =~ s/war/peace/gi; s/pattern/replacement/ • Sed-like Ex: Regular Expression in Perl (5) Substitution ‰ ‰ Regular Expression in Perl (5) Substitution

Computer Center, CS, NCTU 41 Translation Translation - - uash duplicate [a-zA-Z] # rotate right 13 encrypt # delete found but not given a replacement # delete found # $n = “987654” $t = “This is a secret”; $t =~ tr/A-Za-z/N-ZA-Mn-za-m/; $r = “bookkeeper”; $r =~ tr/a-zA-Z//s; $a = “TTesttthiiis ccasse”; # sq $a =~ tr/Ttic/0123/s; # $e = “0es1 1h2s 3asse” $n = “0123456789”; $n =~ tr/0-9/987654/d; A little bit like tr command • tr/search-list/replacement-list/ Ex: Regular Expression in Perl (6) ‰ ‰ Regular Expression in Perl (6)

Computer Center, CS, NCTU 42 You can specify the delimit as regular expression Unmatched string will form a list Ex: ¾ ¾ ¾ $s = “sshd:*:22:22:ssh:/var/empty:/sbin/nologin” @fields = split(“:”, $s); split(separator, string) • Related functions Regular Expression in Perl (7) ‰ Regular Expression in Perl (7)

Computer Center, CS, NCTU 43 SubroutineSubroutine tion arguments, and is private to The value of the last statement will be returned my ($a, $b) = @_; $a if > $b; return $b; the subroutine $_[0], $_[1], …, $[$#_] to access individual arguments Pass by value Either single scalar value or a list @_ contains the subroutine’s invoca sub max { } (20, 8); print &max • • • • Definition Return value Arguments Subroutine (1) ‰ ‰ ‰ Subroutine (1)

Computer Center, CS, NCTU 45 any subroutines calls in the local($n1, $n2) = @_; my ($n3) = add; ($n2, $n1, $n3); return ($n1 + $n2); return same block Use “local” create a list of semi-private variables to Use “my” operator to create a list of private variables Private, but visible within ¾ ¾ ¾ Private variables Semi-private variables sub add; sub sub rev2 { } sub add { } • • Variables in subroutine Subroutine (2) ‰ Subroutine (2)

Computer Center, CS, NCTU 46 FileFile # close file handler open and close open and close - - STDIN, STDOUT, STDERR open FILEHD, “filename”; open FILEHD, “>filename”; open FILEHD, “>>filename”; # open for read # open for write # open for append || dieopen FILEHD, “filename” “error-message: $!”; • open FH, “>>file”; print FH ”abc”; close FH; # output “abc”to file handler FH Automatically opened file handlers Open Open with status checked Use to read from file handlers, just like Output ex: File (1) ‰ ‰ ‰ ‰ ‰ File (1)

Computer Center, CS, NCTU 48 # @a = @b After the file handler closed, start redirection. ¾ Open with redirection for read Open with redirection for write chdir function Globbing open FD, “who |”; open FD, “| mail –s \“Test Mail\” [email protected]”; close FD; chdir “/home” || die “cannot cd to /home ($!)”; @a = ; @b = glob(“/etc/host*”); • • • • Open with redirection Directory File (2) ‰ ‰ File (2)

Computer Center, CS, NCTU 49 rename a file Î create a directory remove a directory change file modes change ownership create a hard link create a symbolic link create a symbolic Î Î Î Î Î Î remove files Î File and Directory Manipulation File and Directory Manipulation - - link(origin, link-file) symlink(origin, link-file) unlink(“data1.dat”, “hello.pl”); unlink(“*.o”); 0777); mkdir(“test”, • • rmdir(dirname) chmod(mode, filename) chown(UID, GID, filename) unlink(filename-list) rename(old-filename, new-filename) mkdir(dirname, mode) Create a link File (3) ‰ ‰ ‰ ‰ ‰ ‰ ‰ File (3)

Computer Center, CS, NCTU 50 SortSort positive negative , 0 and # means the same # means $b, $a , $b and return $a return -1; # means $a, $b return 0; return 1; } else { } } elsif($a == $b) { if($a < $b) { } @list = (1, 2, 4, 8, 16, 32); @sorted = sort {$a <=> $b} @list; { sub by_number Without any modification, sort is based on ASCII code Sort by number, you can do the following You can sort by specifying your own method, defined as subroutine, use Sort ‰ ‰ ‰ Sort

Computer Center, CS, NCTU 52 CPANCPAN 模組 http://www.cpan.org http://search.cpan.org/ http://perl.hcchien.org/app_b.html p5-* Use “make search key” to find them out http://www.newzilla.org/programming/2005/03/16/CPAN/ • • • • • • Comprehensive Perl Archive Network 常用的五十個 CPAN /usr/ports Contributing to CPAN CPAN (1) ‰ ‰ ‰ ‰ CPAN (1)

Computer Center, CS, NCTU 54 perldoc LWP::Simple to find the in e results are the same as module libwww make search name=“p5-” The LWP::Simple is in the in is The LWP::Simple Use freebsd ports tree Install it When you search the module name, th page manual Search the name of perl modules in CPAN pages installed, you can use such as manual • • • • • • Install CPAN Use CPAN CPAN (2) CPAN (2) ‰ ‰

Computer Center, CS, NCTU 55 #!/usr/bin/perl use HTTP::Proxy; use HTTP::Recorder; my $proxy = HTTP::Proxy->new(); # create a new HTTP::Recorder object my $agent = new HTTP::Recorder; # set the log file (optional) $agent->file(“/tmp/myfile”); # set HTTP::Recorder as the agent for the proxy $proxy->agent($agent); # start proxy $proxy->start(); A simple HTTP Proxy CPAN (3) ‰ CPAN (3)

Computer Center, CS, NCTU 56 Complex Data Structure Complex Data Structure

Computer Center, CS, NCTU 57 $scalarref = \$foo; $arrayref = \@ARGV; $hashref = \%ENV; $coderef = \&subroutine; $bar = $$scalarref; push(@$arrayref, $filename); $$arrayref[0] = "January"; $$hashref{"KEY"} = "VALUE"; &$coderef(1,2,3); • • • • • • • • • Create reference: store address of a variable Use reference Reference ‰ ‰

Computer Center, CS, NCTU 58 5 [2] 2 4 [1] the 1st -> cannot be ignored Î 1 3 [0] $a[0] $a[1] $arrayref = [1, 2, 3]; $arrayref = [1, $foo = $$arrayref[1]; @a = ([1, 2], [3, 4, 5]); $a[0][1] == 2 $$arrayref[2][1] == ‘b’ Another way to use reference by -> operator $arrayref -> [2] ->[1] == ‘b’ $arrayref -> [2][1] == ‘b’ • • • • • • • • Anonymous array 2D array $arrayref = [1, 2, ['a', 'b', 'c']]; Multi-dimensional Array ‰ ‰ ‰

Computer Center, CS, NCTU 59 age => {john => 20, mary => 22}, age => {john 20, mary => 1}, {john => 0, mary => ident [ 99, 98 ], => NA_score $$hashref{john} == 20 • $hashref = { john => 20, mary => 22}; %student = ( ); $student{age}{john} == 20 $student{ident}{mary} == 1 $student{NA_score}[1] == 98 Anonymous hash ‰ ‰ ‰ ‰ ‰

Computer Center, CS, NCTU 60 $coderef = sub { print "Boink $_[0]!\n" }; &$coderef (“XD”); Anonymous subroutine ‰ ‰

Computer Center, CS, NCTU 61 # the default name space package main; $life = 3; package Mouse; $life = 1; package main; # switch to our package print “$life\n”; # switch back # shows 3 Package – A different name space Package – A ‰

Computer Center, CS, NCTU 62 The main script, will be run as ./main.pl object Definition of Mouse Î Î Tell perl load the object definition in Mouse.pm to Create new object instance and store the reference to this object in $mouse 1. 2. Pass “Mickey” to the constructor “new” Call method and pass $mouse as the 1st argument main.pl Mouse.pm • • We have two files in the same directory In main.pl, #!/usr/bin/perl -w use Mouse; $mouse = new Mouse( “Mickey” ); $mouse -> speak; print “Age: ”, $mouse->{age}, "\n"; Perl Object Usage ‰ ‰

Computer Center, CS, NCTU 63 Data structure for this object Retrieve its object data Class name used in creating object Constructor Associate the reference $self to class Mouse, so we can call methods of Mouse on this reference, eg. $self->speak Return the blessed reference $self $self, $class; 1. 2. Perl module must return true at the end of script my $class = shift; my $self = { name => $_[0], age 10, }; bless my $self = shift; print “My name is ”, $self->{name}, “\n”; package Mouse; sub new { } sub speak { } 1; Perl Object Definition: Mouse.pm ‰

Computer Center, CS, NCTU 64 ReferenceReference ReadingReading orelly/perl/sysadmin/ Document Document - - 學習手札 Perl –f PerlFunc perldoc –q FAQKeywords perldoc IO::Select perldoc http://perl.hcchien.org/TOC.html http://linux.tnc.edu.tw/techdoc/perl_intro/ http://www.unix.org.ua/ • • • • • • • • • Book Manual pages perldoc Webs Reference (1) ‰ ‰ ‰ ‰ Reference (1)

Computer Center, CS, NCTU 66 brief introduction and overview how to execute perl data structure operators and precedence subroutines functions built-in predefined variables syntax regular expression File I/O Format manual pages manual pages Î Î Î Î Î Î Î Î Î Î Î - - man perl man perlintro man perlrun man perldate man perlop man perlsub man perlfunc man perlvar man perlsyn man perlre man perlopentut man perlform • • • • • • • • • • • • Man Page Reference (2) ‰ Reference (2)

Computer Center, CS, NCTU 67 要來得深入的多 要照下列順序讀 , othrtut, port, locale, uniintro, , othrtut, , modstyle, modinstall, newmod, retut, boot, toot, tooc, boot, style, retut, boot, toot, tooc, style, perldoc Programming Perl perldoc perldoc - - , 瞭解的會比 大師的話,說 trap, debtut, faq[1-9]?, syn, data, op, sub, func, opentut, packtut, pod, trap, debtut, faq[1-9]?, syn, data, op, podspec, run, diag, lexwarn, debug, var, re, ref, form, obj, tie, ipc, fork, number, thrtut dbmfilter, unicode, ebcdic, sec, mod, modlib util, compile, filter, embed, debguts, xstut, xs, clib, guts, call, api, intern, iol, apio, hack. 這樣讀完 intro, toc, reftut, dsc, lol, requick, intro, toc, reftut, dsc, • • Autrijus Reference (3) ‰ Reference (3)

Computer Center, CS, NCTU 68 AppendixAppendix itself with execution result to execute the command specified Process Process - - ($who, $where, $when) = /^(\S+)\s+(\S+)\s+(.*)$/; print “$who on $where at $when”; in the argument STDIN, STDOUT, and STDERR are inherited from the perl process system() will fork a /bin/sh shell system() will fork a /bin/sh shell Execute the command and replace Just as fork(2) system(“date”); ; who > $savehere”); system(“date { $_ (`who`) foreach } • • • • system() function Backquote fork() function Appendix (1) ‰ ‰ ‰ Appendix (1)

Computer Center, CS, NCTU 70 GNORE”, or your subroutine name without prefix “SIG” as the key Signals Signals - - print “I catch you!\n”; print “I catch Using %SIG predefined hash Using signal name in signal(3) kill(signal, pid-list) Ex: $SIG{‘INT’}, $SIG{‘TERM’} Set the value to “DEFAULT”, “I $SIG{‘TERM’} = ‘my_TERM_catcher’; $SIG{‘TERM’} sub my_TERM_catcher { } kill(1, 234, 235); # or kill(‘HUP’, 234, 235); • • • • • Catch the signal in your program Sending the signal Appendix (2) ‰ ‰ Appendix (2)

Computer Center, CS, NCTU 71 tpwnam, getgrent, setgrent, … in functions sten, getsockopt, setsockopt, … in functions - - Built Built - - chomp, chop, index, length, sprintf, substr, … … cos, sqrt, abs, exp, log, hex, int, oct, rand, sin, sort, keys, values, delete pop, shift, push, open, close, read, write, print, printf, … gmtime, localtime, time, times bind, socket, accept, connect, li getpwent, setpwent, getpwuid, ge • • • • • • • Scalars Numeric For @ and % I/O Time-related Network User and group information Appendix (3) ‰ ‰ ‰ ‰ ‰ ‰ ‰ Appendix (3)

Computer Center, CS, NCTU 72