1 / 76

PERL

PERL. Perl Power!. Who uses Perl? Sites with heavy traffic that need excellent text processing capabilities   Compiler optimization is also done in Perl  System Administrators(the impatient ones, to be exact.) The Swiss Army Knife Language

sian
Télécharger la présentation

PERL

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PERL

  2. Perl Power! • Who uses Perl? • Sites with heavy traffic that need excellent text processing capabilities   • Compiler optimization is also done in Perl  • System Administrators(the impatient ones, to be exact.) • The Swiss Army Knife Language •  It can perform a lot of things,from simple scripting to number-crunching • "There are many ways to do it" --> the Perl Philosophy • Similarities with other programming language • There is a striking similarity with C---after all, this is written in C! • Shell scripting in UNIX heavily influenced Perl 

  3. The Fundamentals • Scalar Data Types Revisited • Lists and Arrays • Control Structures and Code Blocks • Subroutines • Regular Expressions (a.k.a. Pattern Matching)

  4. Scalar Data Types • Scalar as String or Scalar as Integer? Both! • Could be: • $name = "Gizmo" ; • $age =3 ;  • $height = 3.141591 • $name = $age = 'This is a new string, overwriting both variables $name and $age!' • So what's the big deal with the '$'? • It is required for every scalar variable

  5. Basic Operations • arithmetic • the usual +,-,*, /, % • e.g  • $ave = $grade/$units • concatenation • if in Python, we use +, here we use '.' (a period) • e.g: $string = $firstname.$lastname;

  6. Basic Operations • the 'x' operator • if (again, in Python), we use '*' to duplicate strings, here we use 'x'. • e.g: $manylaughs = "he"x1000;

  7. The substring method • Syntax; • $somesub = substring($original, startingpoint,lengthofsubstring); • e.g: $firstfour = substring($somestring, 0,4); • this is how you access the individual characters of a string • the basic data type is a scalar---string or number only.  • character is not basic data type, so it has to be extracted first from a string.

  8. Putting Comments • Like in Python, the comments are      # enter comments here (See the legacy of Perl over Python? :P) 

  9. Try this one!     (To print, use print method, just like in Python) #!/usr/bin/perl -w $name = "Slim Shady"; $num = 525600; $message = $name." knows that there are ".$num." minutes in a year.\nErgo, he knows that there are ".$num/60."hours in a year." ; print $message;

  10. Formatted Output There is also a printf method in Perl syntax:     printf "%format", some variable;

  11. Basic Input • Consider the snippet below first: • $input = <STDIN>; • chomp($input); • STDIN is a built-in file handle.  • if you type into a console, the data you've entered is directed into STDIN • $input gets the value of STDIN

  12. Basic Input • chomp is just optional • it only trims the trailing newlines of the input • What if I use chop() instead? • yes it can also trim the newline ---but everytime we  call chop() removes ANY character at the end. Be careful.  

  13. Quotes Matter! • What is the difference between • $name = "I shall return." ; • print "$name"; • print '$name';

  14. Quotes Matter! • using single quotes print things LITERALLY. • Ergo,  doing a print '$name' will really print '$name'. • and yes, you've guessed it, using double quotes ("") enable variable interpolation (err, the opposite of literal) • print "$name" really prints "I shall return."

  15. Control Structures and Blocks • The Control Structures in Perl tend to be like those in C. • Conditional Statements: •  if • if-else • if-elsif-else • unless  

  16. Conditional Statement: if • if - same as in C. • e.g. • $gas_money=5;if ($gas_money < 10){  print "You will not get much gas for less than 10 bucks!";}print "Gas is expensive.";

  17. Conditional Statement:if-else • if the "if" condition is not true. If you have just one other option, simply use an else statement after the if statement, like this: • if ($gas_money < 10){  print "You will not get much gas for less than 10 bucks!";}else{ print "You have enough money for now.";}print "Gas is expensive.";

  18. Conditional Statement: if-elsif-else • If you want to check for a couple of conditions, you can use elsif to do another check and leave the else code as a last resort. • if (($gas_money < 10) && ($gas_money > 0)){  print "You will not get much gas for less than 10 bucks!";} elsif ($gas_money <= 0){ print "You need to get some money!";} else{ print "You have enough money for now.";}print "Gas is expensive.";

  19. Conditional Statement: unless •  Sort of like the opposite of the if statement: • unless ($gas_money == 10){ print "You need exact change. 10 bucks please.";}

  20. There are many ways to Loop it! • for - same as in C • syntax: • for (starting assignment; test condition; increment){ code to repeat}

  21. There are many ways to Loop it! •  using for in Perl  • e.g. for ($i = 0; $i < 10; ++$i){print "$i\n";}

  22. There are many ways to Loop it! • foreach - to go through each line of an array or any list-like structure(such as each line of a file) • e.g. • @food = ("sinigang","adobo","beef steak") • foreach $pagkain (@food) { •       print " ang sarap naman ng "."$pagkain!\n"; • }

  23. There are many ways to Loop it! • while -The while loop repeats a portion of code, but it repeats it until the condition you provide comes back false • syntax: • while(some condition) • {code to repeat} • do-while: • do{code to repeat} • while(some condition)

  24. There are many ways to Loop it! • using while while($ctr < ){ print “$ctr\n”; $ctr++; }# end while

  25. Subroutines • functions in Perl are called subroutines. • Always pass by value • to call a subroutine we do this: • &sub1; • Note that there are no "()" after. We can deal with that later.

  26. Subroutines • To define a subroutine:          sub sub1{              /*Then enter logic here*/         } • But where are the parameters?

  27. Subroutines • Parameters are passed using the '@_' built-in variable, containing the value of the recently evaluated array. e.g.:  sub Sub1{      ($param1,$param2,...,$param) = @_;  } 

  28. Subroutines • Bring into memory Dynamic and Static Scoping • Static: variables are "seen" from the place where it was declared. Any other function also defined by the same place can also see the variable

  29. Subroutines • Are we really sure that the parameters won't go out of scope? • if the parameter's identifier is used outside the subroutine, would there be a difference e.g.:   sub Sub1{      ($param1,$param2,...,$param) = @_;  } 

  30. Subroutines • Bring into memory Dynamic and Static Scoping • Dynamic: Values of the variables defined somewhere can still be seen even after it has "escaped" the place where it was defined.

  31. Subroutines: Using my and local • my keyword: • variables defined with this keyword can only be seen by the defining method • sub Sub1{ • my ($var1) = @_; • sub Sub2{ •  print $var1; #--> error! • }  • } 

  32. Subroutines: Using my and local • local keyword: • can be seen by the defining method, and other methods defined with the variable • sub Sub1{ • local ($var1) = @_; • sub Sub2{ • print $var1;  • }  • } 

  33. Subroutines: Returning Values • the usual return in C and Java • without the return, the last evaluated expression will be returned • this exhibits "Dynamic Scoping", too. 

  34. Exercise! Regular Expressions!!! • At least one a,then any number of b /a+b*/ Any 5 characters including new line /(.|\n){5}/ Match a string resembling an if statement in C if () /^if(\w+)/ The same word written in two or more times in a row (with possibly varying intervening whitespace), where a word is defind as a nonempty swquence of nonwhitespace character. / (^|\s)(\S+)(\s+\2)+(\s|$)/

  35. Answer: • sub fac{ • my ($n) = @_; • if ($n <= 1){return 1;} • else { • return &fac($n-1)*$n; • } • } • %hasher; • for $i (1..9){ • $hasher{$i} = &fac($i); • print "$i\'s factorial: ",$hasher{$i}, "\n"; • }

  36. Regular Expressions • This is the most powerful aspect of Perl • With great power comes great responsibility • “If Perl is a gun, then THIS is the bullet!” • One amazing search engine

  37. One Basic Example $var = “Starry starry night, paint your\n palette blue and gray.”; if ($var =~ /rry s/){ print “Yey, something matched”; } else{ print “nah, nothing matched.”; } So what will it print? Why?

  38. Examining the Pattern • our patterns that we wish to find are located inside the ‘//’ • /rry s/ • also note that there are no quotes “around” the pattern

  39. Examining the Pattern • First, we assigned $var some string. • Then comes a conditional • if ($var =~ /rry s/){ • #perform operations here • } • else{ • #perform other operations here • } • What does that expression mean?

  40. Examining the Pattern -‘=~’ • We introduce the matching operator • checks if a given variable contains the pattern described • So if $var is “Starry starry night, paint your palette blue and gray.”, • there really is some sequence of characters matching the pattern /rry s/ • it returns true!

  41. Examining the Pattern • But what if /rRy s/? • patterns are CASE SENSITIVE • Ergo, it will return false with respect to $var

  42. Quantifiers • They check the multiplicity of the character before it • added at the end • form: • /(…)QUANTIFIER /

  43. More Patterns: QUANTIFIERS • introducing ‘.’ • e.g. /Sta./ as our pattern • the ‘dot’ means “any” non-null character, except a newline! • so, /Sta./ matches “Star” in $var!

  44. Quantifiers • Introducing ‘*’ • It means any number of the character before it(even 0) • so, if our pattern is /Stare*/, IT WILL RETURN TRUE!. • BUT WHY? • * checks the letter ‘e’ before Star • but it appears nowhere in $var, still qualifying for ‘*’’s logic

  45. Quantifiers • Yes, yes, ‘*’ can be pretty cumbersome for all of us at times • introducing ‘+’ • it assures that there is at least one instance of that character

  46. Quantifiers • e.g.: • if we wish to find the pattern /Stare+/, it will now return false • + checks if there exists at least ONE or MORE ‘e’, given that it matches the pattern. • if our pattern, for variety, is /gray+/, it will return TRUE.

  47. Quantifiers • Introducing ‘?’ • it means “to find for something that occurs ONCE or NONE AT ALL” • i.e., if the character is OPTIONAL • e.g. • $string = “colour”; • /colou?r/ will return true

  48. Grouping Characters Together • We use ‘( )’ to group characters • Similar with the mathematical grouping notation • so if our pattern is /(nightt)+/ • our search will return false with respect with $var. • To search for ‘(‘ or ‘)’ itself, add \ in front.

  49. Alternations (using ‘or’) • /x|y/, if you want to find EITHER x or y

  50. Summary • /x*/ - check any number of x’s • /x+/ - check any number of “occurring” x’s • /x?/ - check if x is optional • /(xyz)+/ - groups characters as if it is a single entity; checks any number of occurring (xyz)’s • /…|…/ - it’s like ORing patterns • AND ONE NOTE: these “metacharacters” must be preceded by a \ to actually search them.

More Related