Скачать презентацию Introduction to Perl Part I By Cédric Notredame Скачать презентацию Introduction to Perl Part I By Cédric Notredame

8335eb19f70960407ebc0d145a0a1efd.ppt

  • Количество слайдов: 55

Introduction to Perl Part I By: Cédric Notredame (Adapted from BT Mc. Innes) Introduction to Perl Part I By: Cédric Notredame (Adapted from BT Mc. Innes)

What is Perl? n Perl is a Portable Scripting Language n No compiling is What is Perl? n Perl is a Portable Scripting Language n No compiling is needed. n Runs on Windows, UNIX, LINUX and cygwin n Fast and easy text processing capability n Fast and easy file handling capability n Written by Larry Wall n “Perl is the language for getting your job done. ” n Too Slow For Number Crunching n Ideal for Prototyping 2

How to Access Perl n To install at home n Perl Comes by Default How to Access Perl n To install at home n Perl Comes by Default on Linux, Cygwin, Mac. OSX n www. perl. com Has rpm's for Linux n www. activestate. com Has binaries for Windows n Latest Version is 5. 8 n To check if Perl is working and the version number n % perl -v 3

Resources For Perl n Books: n Learning Perl n n n By Larry Wall Resources For Perl n Books: n Learning Perl n n n By Larry Wall Published by O'Reilly Programming Perl n n By Larry Wall, Tom Christiansen and Jon Orwant Published by O'Reilly n Web Site n http: //safari. oreilly. com n Contains both Learning Perl and Programming Perl in ebook form 4

Web Sources for Perl n Web n www. perl. com n www. perldoc. com Web Sources for Perl n Web n www. perl. com n www. perldoc. com n www. perl. org n www. perlmonks. org 5

The Basic Hello World Program n which perl n pico hello. pl n Program: The Basic Hello World Program n which perl n pico hello. pl n Program: #! /…path…/perl -w print “Hello World!n”; n Save this as “hello. pl” n Give it executable permissions n chmod a+x hello. pl n Run it as follows: n . /hello. pl 6

“Hello World” Observations n “. pl” extension is optional but is commonly used n “Hello World” Observations n “. pl” extension is optional but is commonly used n The first line “#!/usr/local/bin/perl” tells UNIX where to find Perl n “-w” switches on warning : not required but a really good idea 7

Variables and Their Content Variables and Their Content

Numerical Literals n Numerical Literals 6 Integer n 12. 6 Point n 1 e Numerical Literals n Numerical Literals 6 Integer n 12. 6 Point n 1 e 10 Notation n 6. 4 E-33 Notation n 4_348 n long numbers Floating Scientific Underscores instead of commas for 9

String Literals n String Literals “There is more than one way to do it!” String Literals n String Literals “There is more than one way to do it!” n 'Just don't create a file called -rf. ' n “Beauty? n. What's that? n” n “Real programmers can write assembly in any language. ” n § Quotes from Larry Wall 10

Types of Variables n Types of variables: n Scalar variables : $a, $b, $c Types of Variables n Types of variables: n Scalar variables : $a, $b, $c n Array variables : @array n Hash variables : %hash n File handles : STDIN, STDOUT, STDERR n Variables do not need to be declared n Variable type (int, char, . . . ) is decided at run time n $a = 5; # now an integer n $a = “perl”; # now a string 11

Operators on Scalar Variables n Numeric and Logic Operators n Typical : +, -, Operators on Scalar Variables n Numeric and Logic Operators n Typical : +, -, *, /, %, ++, --, +=, -=, *=, /=, ||, &&, ! ect … n Not typical: ** for exponentiation n String Operators n Concatenation: “. ” - similar to strcat $first_name = “Larry”; $last_name = “Wall”; $full_name = $first_name. “ “. $last_name; 12

Equality Operators for Strings n Equality/ Inequality : eq and ne $language = “Perl”; Equality Operators for Strings n Equality/ Inequality : eq and ne $language = “Perl”; if ($language == “Perl”). . . # Wrong! if ($language eq “Perl”). . . #Correct n Use eq / ne rather than == / != for strings 13

Relational Operators for Strings n Greater than n Numeric : > String : gt Relational Operators for Strings n Greater than n Numeric : > String : gt n Greater than or equal to n Numeric : >= ge String : n Less than n Numeric : < String : lt n Less than or equal to n Numeric : <= String : le 14

String Functions n Convert to upper case n $name = uc($name); n Convert only String Functions n Convert to upper case n $name = uc($name); n Convert only the first char to upper case n $name = ucfirst($name); n Convert to lower case n $name = lc($name); n Convert only the first char to lower case n $name = lcfirst($name); 15

A String Example Program n Convert to upper case n $name = uc($name); n A String Example Program n Convert to upper case n $name = uc($name); n Convert only the first char to upper case n $name = ucfirst($name); n Convert to lower case n $name = lc($name); n Convert only the first char to lower case n $name = lcfirst($name); #!/usr/bin/perl $var 1 = “larry”; $var 2 = “moe”; $var 3 = “shemp”; …… Output: Larry, MOE, s. HEMP 16

A String Example Program #!/usr/local/bin/perl $var 1 = “larry”; $var 2 = “moe”; $var A String Example Program #!/usr/local/bin/perl $var 1 = “larry”; $var 2 = “moe”; $var 3 = “shemp”; print ucfirst($var 1); print uc($var 2); print lcfirst(uc($var 3)); 's. HEMP' # Prints 'Larry' # Prints 'MOE' # Prints 17

Variable Interpolation n Perl looks for variables inside strings and replaces them with their Variable Interpolation n Perl looks for variables inside strings and replaces them with their value $stooge = “Larry” print “$stooge is one of the three stooges. n”; Produces the output: Larry is one of the three stooges. n This does not happen when you use single quotes print '$stooge is one of the three stooges. n’; Produces the output: $stooge is one of the three stooges. n 18

Character Interpolation n List of character escapes that are recognized when using double quoted Character Interpolation n List of character escapes that are recognized when using double quoted strings n n n n t r newline tab carriage return n Common Example : n print “Hellon”; # prints Hello and then a return 19

Numbers and Strings are Interchangeable n If a scalar variable looks like a number Numbers and Strings are Interchangeable n If a scalar variable looks like a number and Perl needs a number, it will use it as a number $a = 4; # a number print $a + 18; # prints 22 $b = “ 50”; # looks like a string, but. . . print $b – 10; # will print 40! 20

Control Structures: Loops and Conditions Control Structures: Loops and Conditions

If. . . else. . . statements if ( $weather eq “Rain” ) { If. . . else. . . statements if ( $weather eq “Rain” ) { print “Umbrella!n”; } elsif ( $weather eq “Sun” ) { print “Sunglasses!n”; } else { print “Anti Radiation Armor!n”; } 22

Unless. . . else Statements n Unless Statements are the opposite of if. . Unless. . . else Statements n Unless Statements are the opposite of if. . . else statements. unless ($weather eq “Rain”) { print “Dress as you wish!n”; } else { print “Umbrella!n”; } n And again remember the braces are required! 23

While Loop n Example : $i = 0; while ( $i <= 1000 ) While Loop n Example : $i = 0; while ( $i <= 1000 ) { print “$in”; $i++; } 24

Until Loop n The until function evaluates an expression repeatedly until a specific condition Until Loop n The until function evaluates an expression repeatedly until a specific condition is met. n Example: $i = 0; until ($i == 1000) { print “$in”; $i++; } 25

For Loops n Syntax 1: n for ( $i = 0; $i <= 1000; For Loops n Syntax 1: n for ( $i = 0; $i <= 1000; $i=$i+2 ) { print “$in”; } n Syntax 2: n for $i(0. . 1000) { print “$in”; } 26

Moving around in a Loop n next: ignore the current iteration n last: terminates Moving around in a Loop n next: ignore the current iteration n last: terminates the loop. n What is the output for the following code snippet: for ( $i = 0; $i < 10; $i++) { if ($i == 1 || $i == 3) { next; } elsif($i == 5) { last; } else {print “$in”; } } 27

Answer 0 2 4 Answer 0 2 4

Exercise n Use a loop structure and code a program that produces the following Exercise n Use a loop structure and code a program that produces the following output: A AA AAABAA AAABAAAB …. . TIP: $chain = $chain. “A”; 29

Exercise #! /usr/bin/perl for ($i=0, $j=0; $i<100; $i++) { if ( $j==3){$chain. =“B”; $j=0; Exercise #! /usr/bin/perl for ($i=0, $j=0; $i<100; $i++) { if ( $j==3){$chain. =“B”; $j=0; } else {$chain. =“A”; $j++; } print “$chainn”; } 30

Exercise: Generating a Random Sample n A study yields an outcome between 0 and Exercise: Generating a Random Sample n A study yields an outcome between 0 and 100 for every patient. You want to generate an artificial random study for 100 patients: Patient 1 99 Patient 2 65 Patient 3 89 …. Tip: - use the srand to seed the random number generator -use rand 100 to generate values between 0 and 100 : rand 100 31

Exercise for ($i=0; $i<100; $i++) { $v=rand 100; #print “Patient $i $vn”; printf “Patient Exercise for ($i=0; $i<100; $i++) { $v=rand 100; #print “Patient $i $vn”; printf “Patient %d %. 2 fnn”, $i, $v; #%s : chaines, strings #%d : integer #%f : floating points } 32

Collections Of Variables: Arrays Collections Of Variables: Arrays

Arrays n Array variable is denoted by the @ symbol n @array = ( Arrays n Array variable is denoted by the @ symbol n @array = ( “Larry”, “Curly”, “Moe” ); n To access the whole array, use the whole array n print @array; # prints : Larry Curly Moe n Notice that you do not need to loop through the whole array to print it – Perl does this for you 34

Arrays cont… n Array Indexes start at 0 !!!!! n To access one element Arrays cont… n Array Indexes start at 0 !!!!! n To access one element of the array : use $ n Why? Because every element in the array is scalar n print “$array[0]n”; # prints : Larry n Question: n What happens if we access $array[3] ? n n Answer 1 : Value is set to 0 in Perl Answer 2: Anything in C!!!!! 35

Arrays cont. . . n To find the index of the last element in Arrays cont. . . n To find the index of the last element in the array print $#array; # prints 2 in the previous # example n Note another way to find the number of elements in the array: $array_size = @array; n $array_size now has 3 in the above example because there are 3 elements in the array 36

Sorting Arrays n Perl has a built in sort function n Two ways to Sorting Arrays n Perl has a built in sort function n Two ways to sort: n Default : sorts in a standard string comparisons order n sort LIST n Usersub: create your own subroutine that returns an integer less than, equal to or greater than 0 n Sort USERSUB LIST n The <=> and cmp operators make creating sorting subroutines very easy 37

Numerical Sorting Example #!/usr/local/bin/perl -w @unsorted. Array = (3, 10, 76, 23, 1, 54); Numerical Sorting Example #!/usr/local/bin/perl -w @unsorted. Array = (3, 10, 76, 23, 1, 54); @sorted. Array = sort numeric @unsorted. Array; print “@unsorted. Arrayn”; # prints 3 10 76 23 1 54 print “@sorted. Arrayn”; # prints 1 3 10 23 54 76 sub numeric { return $a <=> $b; } # Numbers: $a <=> $b : # Strings: $a cpm $b : -1 if $a<$b , 0 if $a== $b, 1 if $a>$b 38

String Sorting Example #!/usr/local/bin/perl -w @unsorted. Array = (“Larry”, “Curly”, “moe”); @sorted. Array = String Sorting Example #!/usr/local/bin/perl -w @unsorted. Array = (“Larry”, “Curly”, “moe”); @sorted. Array = sort { lc($a) cmp lc($b)} @unsorted. Array; print “@unsorted. Arrayn”; # prints Larry Curly moe print “@sorted. Arrayn”; # prints Curly Larry moe 39

Foreach n Foreach allows you to iterate over an array n Example: foreach $element Foreach n Foreach allows you to iterate over an array n Example: foreach $element (@array) { print “$elementn”; } n This is similar to : for ($i = 0; $i <= $#array; $i++) { print “$array[$i]n”; } 40

Sorting with Foreach n The sort function sorts the array and returns the list Sorting with Foreach n The sort function sorts the array and returns the list in sorted order. n Example : @array( “Larry”, “Curly”, “Moe”); foreach $element (sort @array) { print “$element ”; } n Prints the elements in sorted order: Curly Larry Moe 41

Exercise: Sorting According to Multiple Criterion n Use the following initialization to sort individuals Exercise: Sorting According to Multiple Criterion n Use the following initialization to sort individuals by age and then by income: n Syntax @sorted. Array = sort numeric @unsorted. Array; sub numeric { return $a <=> $b; } Data @index=(0, 1, 2, 3, 4); @name=(“V”, “W”, ”X”, ”Y”, ”Z”); @age=(10, 20, 15, 20, 10); @income=(100, 670, 280, 800, 400); n Output: Name X Age A Income I … Tip: -Sort the index, using information contained in the other arrays. 42

Exercise: Sorting According to Multiple Criterion n @index=(0, 1, 2, 3, 4, 5); @name=(“V”, Exercise: Sorting According to Multiple Criterion n @index=(0, 1, 2, 3, 4, 5); @name=(“V”, “W”, ”X”, ”Y”, ”Z”); @age=(10, 20, 15, 20, 10); @income=(100, 670, 280, 800, 400); foreach $i ( sort my_numeric @index) { print “$name[$i] $age[$i] $income[$i]; } sub my_numeric { if ($age[$a] == $age[$b]) {return $income[$a]<=>$income[$b]; } else {return $age[$a]<=>$age[$b]; } } 43

Manipulating Arrays Manipulating Arrays

Strings to Arrays : split n Split a string into words and put into Strings to Arrays : split n Split a string into words and put into an array @array = split( /; /, “Larry; Curly; Moe” ); @array= (“Larry”, “Curly”, “Moe”); # creates the same array as we saw previously n Split into characters @stooge = split( //, “curly” ); # array @stooge has 5 elements: c, u, r, l, y 45

Split cont. . n Split on any character @array = split( /: /, “ Split cont. . n Split on any character @array = split( /: /, “ 10: 20: 30: 40”); # array has 4 elements : 10, 20, 30, 40 n Split on Multiple White Space @array = split(/s+/, “this a test”; # array has 4 elements : this, a, test n More on ‘s+’ later 46

Arrays to Strings n Array to space separated string @array = (“Larry”, “Curly”, “Moe”); Arrays to Strings n Array to space separated string @array = (“Larry”, “Curly”, “Moe”); $string = join( “; “, @array); # string = “Larry; Curly; Moe” n Array of characters to string @stooge = (“c”, “u”, “r”, “l”, “y”); $string = join( “”, @stooge ); # string = “curly” 47

Joining Arrays cont… n Join with any character you want @array = ( “ Joining Arrays cont… n Join with any character you want @array = ( “ 10”, “ 20”, “ 30”, “ 40” ); $string = join( “: ”, @array); # string = “ 10: 20: 30: 40” n Join with multiple characters @array = “ 10”, “ 20”, “ 30”, “ 40”); $string = join(“->”, @array); # string = “ 10 ->20 ->30 ->40” 48

Arrays as Stacks and Lists n To append to the end of an array Arrays as Stacks and Lists n To append to the end of an array : @array = ( “Larry”, “Curly”, “Moe” ); push (@array, “Shemp” ); print $array[3]; # prints “Shemp” n To remove the last element of the array (LIFO) $elment = pop @array; print $element; # prints “Shemp” n @array now has the original elements (“Larry”, “Curly”, “Moe”) 49

Arrays as Stacks and Lists n To prepend to the beginning of an array Arrays as Stacks and Lists n To prepend to the beginning of an array @array = ( “Larry”, “Curly”, “Moe” ); unshift @array, “Shemp”; print $array[3]; # prints “Moe” print “$array[0]; # prints “Shemp” n To remove the first element of the array $element = shift @array; print $element; # prints “Shemp” n The array now contains only : n “Larry”, “Curly”, “Moe” 50

Exercise: Spliting n Instructions n Remove n n shift: beginning, pop: end Add n Exercise: Spliting n Instructions n Remove n n shift: beginning, pop: end Add n Unshift: beginning, push: end n Use split, shift and push to turn the following string: “The enquiry 1 was administered to five couples” “The enquiry 2 was administered to six couples” “The enquiry 3 was administered to eigh couples” Into …. “five couples were administered the enquiry 1” 51

Exercise: Spliting n Use split, shift and push to turn the following string: $s[0]= Exercise: Spliting n Use split, shift and push to turn the following string: $s[0]= “The enquiry 1 was administered to five couples”; $s[1]= “The enquiry 2 was administered to six couples”; $s[2]= “The enquiry 3 was administered to eigh couples”; foreach $s(@s) { @s 2=split (/was administered to/, $s); $new_s=“$s 2[1] were admimistered $s 2[0]”; print “$new_sn”; } 52

Multidimentional Arrays Multidimentional Arrays

Multi Dimensional Arrays n Better use Hash tables (cf later) n If you need Multi Dimensional Arrays n Better use Hash tables (cf later) n If you need to: n @tab=([‘Monday’, ’Tuesday’], [‘Morning’, ’Afternoon’, ’Evening’]); $a=$tab[0][0] # $a == ‘Monday’ $tab 2=(‘midnight’, ‘Twelve’); $tab[2][email protected] 2 # integrate tab 2 as the last row of tab 54

Thank you Thank you