Perl 101 - The Basics of Perl Programming

11,373 views

Published on

Published in: Education, Technology
0 Comments
8 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
11,373
On SlideShare
0
From Embeds
0
Number of Embeds
49
Actions
Shares
0
Downloads
596
Comments
0
Likes
8
Embeds 0
No embeds

No notes for slide

Perl 101 - The Basics of Perl Programming

  1. 1. Perl -101
  2. 2. Objectives <ul><li>To introduce Perl Scripting Language </li></ul><ul><li>To introduce the concept of regular expressions and pattern matching </li></ul><ul><li>To introduce various file operations in Perl </li></ul>Linux User Group at San Jose State University
  3. 3. Agenda <ul><li>Part 1 (1:30PM to 2:45PM) </li></ul><ul><li>Introduction to Perl </li></ul><ul><li>– Types of Variables </li></ul><ul><li>– I/O Functions </li></ul><ul><li>– Operators </li></ul><ul><li>– String and formatting strings </li></ul><ul><li>– Selectional, iterational and miscellaneous control statements </li></ul><ul><li>Data Structures </li></ul><ul><li>– Arrays and various operations on arrays </li></ul><ul><li>– Hashes and various operations on hashes </li></ul><ul><li>Functions: </li></ul><ul><li>– Subroutines </li></ul><ul><li>– Command line arguments </li></ul>Linux User Group at San Jose State University Part 2 (2:50PM to 3:45PM) Regular Expressions: – Regular Expressions – Meta characters – Character classes – Pattern matching File IO: – Reading, Writing text files – Various file I/O modes Misc: – Installing modules Questions and Answers
  4. 4. What is PERL and where PERL is being used? <ul><li>PERL is scripting language </li></ul><ul><li>PERL is mostly used for extracting information from text files and generating various reports based on that </li></ul><ul><li>PERL is also used for developing web applications using CGI standards </li></ul><ul><li>It is also used for developing scripts of automated testing, system administration etc. </li></ul><ul><li>It is one of the most popular scripting language </li></ul>Linux User Group at San Jose State University
  5. 5. Perl Introduction <ul><li>PERL – Practical Extraction and Report Language </li></ul><ul><ul><li>Developed by Larry Wall in 1987 </li></ul></ul><ul><ul><li>Originally designed for reading text files and preparing reports based on that information </li></ul></ul><ul><ul><li>Combines features of C ,sed, awk and sh </li></ul></ul><ul><ul><li>Gives unlimited data size </li></ul></ul><ul><ul><li>Recursion of unlimited depth </li></ul></ul><ul><ul><li>Sophisticated pattern matching techniques </li></ul></ul><ul><ul><li>Used for web programming </li></ul></ul><ul><ul><li>Widely used for system administration </li></ul></ul><ul><ul><li>Wide range of third party modules </li></ul></ul>Linux User Group at San Jose State University
  6. 6. The PERL Interpreter <ul><li>Perl Interpreter </li></ul><ul><ul><li>Converts the scripts in to a parse tree and executes immediately </li></ul></ul><ul><ul><li>Internally Perl maintains a byte code for execution </li></ul></ul><ul><ul><li>Known as interpreter/ compiler </li></ul></ul>Linux User Group at San Jose State University
  7. 7. PERL - Variables <ul><li>Scalar Variables </li></ul><ul><ul><li>Simple variables containing an element, either a number or a string </li></ul></ul><ul><ul><li>Defined by $ symbol </li></ul></ul><ul><li>Array </li></ul><ul><ul><li>List of scalar variables </li></ul></ul><ul><ul><li>Defined by @ symbol </li></ul></ul><ul><li>Hashes </li></ul><ul><ul><li>Similar to arrays </li></ul></ul><ul><ul><li>Each item is identified by a key value </li></ul></ul><ul><ul><li>Defined by % symbol </li></ul></ul>Linux User Group at San Jose State University
  8. 8. PERL – Scalar Variables <ul><ul><li>Defined by $ Symbol </li></ul></ul><ul><ul><li>Stores either a number or a String </li></ul></ul><ul><ul><li>No declaration required, creation is done when a variable is referred first in the program,known as auto vivification </li></ul></ul><ul><ul><li>Strings and Numbers are interchangeable </li></ul></ul><ul><ul><li>Variable names are case sensitive </li></ul></ul><ul><ul><li>Variable name can have alphabets, numbers and underscore (_) </li></ul></ul><ul><ul><ul><li>Should not start with a number </li></ul></ul></ul><ul><ul><ul><li>Variables starting with _ is special </li></ul></ul></ul>Linux User Group at San Jose State University
  9. 9. PERL - Lists <ul><ul><li>Collection of scalar data, Arrays and Hashes </li></ul></ul><ul><ul><li>Represents a logical group of items </li></ul></ul><ul><ul><li>Scalar data inside ( and ) separated using , represents a list </li></ul></ul><ul><ul><li>A set of operators works on list – called as list operator </li></ul></ul><ul><ul><ul><li>E.g. print </li></ul></ul></ul><ul><ul><ul><li>print (1,2,3) displays 123 </li></ul></ul></ul>Linux User Group at San Jose State University
  10. 10. PERL – Display Functions <ul><li>print </li></ul><ul><ul><li>Unformatted output statement which can print a string, Number or a List </li></ul></ul><ul><ul><li>Default outputs to STDOUT, can be redirected to STDERR or a File </li></ul></ul><ul><ul><li>Returns ‘true’ if successful else ‘false’ [1 represents ‘true’] </li></ul></ul><ul><ul><ul><li>print List </li></ul></ul></ul><ul><ul><ul><li>print FILEHANDLE List </li></ul></ul></ul><ul><li>printf </li></ul><ul><ul><li>Formatted output statement </li></ul></ul><ul><ul><li>By defaults outputs to STDOUT. Can be redirected to STDERR or a File </li></ul></ul><ul><ul><li> printf Format, List </li></ul></ul><ul><ul><li>printf FILEHANDLE, Format, List </li></ul></ul><ul><li>warn </li></ul><ul><ul><li>Outputs a message on the STDERR stream (unbuffered) </li></ul></ul><ul><ul><li>Used to trace error when STDOUT is redirected </li></ul></ul><ul><ul><li>Program is neither terminated nor an exception is thrown </li></ul></ul><ul><ul><ul><li>warn “Message” </li></ul></ul></ul>Linux User Group at San Jose State University
  11. 11. PERL - Operators <ul><li>Assignment Operator </li></ul><ul><li>Auto increment and decrement operators </li></ul><ul><li>Additive operators </li></ul><ul><li>Multiplicative operators </li></ul><ul><li>Exponentiation Operator </li></ul><ul><li>Relational Operators </li></ul><ul><li>Logical Operators </li></ul><ul><li>Range Operator </li></ul><ul><li>Binding Operator </li></ul><ul><li>Arrow operator </li></ul><ul><li>File I/O Operator </li></ul>Linux User Group at San Jose State University
  12. 12. PERL – Operators contd <ul><li>Assignment Operator (=) </li></ul><ul><li>Auto increment and decrement operator (++, --) </li></ul><ul><li>Additive Operator (+, -, .) </li></ul><ul><ul><ul><li>Addition & Subtraction operator </li></ul></ul></ul><ul><ul><ul><li>Concatenation Operator (.) </li></ul></ul></ul><ul><li>Multiplicative Operators </li></ul><ul><ul><li>Multiplication & Division </li></ul></ul><ul><ul><li>Repetition Operator (x) </li></ul></ul><ul><ul><li>Exponential Operator </li></ul></ul>Linux User Group at San Jose State University
  13. 13. PERL – operators contd <ul><li>Relational Operators </li></ul><ul><ul><li>Operating on Numeric data </li></ul></ul><ul><ul><ul><li><, <=, >, >=, ==, !=,  </li></ul></ul></ul><ul><ul><li>Operating on String data </li></ul></ul><ul><ul><ul><li>lt – less than E.g. ($Myname lt $YourName) </li></ul></ul></ul><ul><ul><ul><li>gt – greater than </li></ul></ul></ul><ul><ul><ul><li>le – less than or equal to </li></ul></ul></ul><ul><ul><ul><li>ge – greater than or equal to </li></ul></ul></ul><ul><ul><ul><li>eq – equal to </li></ul></ul></ul><ul><ul><ul><li>ne – not equal to </li></ul></ul></ul><ul><ul><ul><li>cmp – compare (returns -1, 0 , 1) </li></ul></ul></ul><ul><ul><li>Logical Operator </li></ul></ul><ul><ul><ul><li>AND - && or ‘ and ’ </li></ul></ul></ul><ul><ul><ul><li>OR - || or ‘ or ’ </li></ul></ul></ul><ul><ul><ul><li>NOT - not </li></ul></ul></ul>Linux User Group at San Jose State University
  14. 14. PERL – Operators contd <ul><li>Range Operator (..) </li></ul><ul><ul><ul><li>Returns a list of sequence of values </li></ul></ul></ul><ul><ul><ul><ul><li>print (1..50); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>print (a..z); </li></ul></ul></ul></ul><ul><li>Bind Operator (=~, !~) </li></ul><ul><ul><ul><li>Used for binding scalar expressions to a pattern match </li></ul></ul></ul><ul><li>Arrow Operator (->) </li></ul><ul><ul><ul><li>Used to retrieve elements from a reference </li></ul></ul></ul><ul><li>File Operator (<File_Handle>) </li></ul><ul><ul><ul><li>Used for File I/O Operations </li></ul></ul></ul><ul><ul><ul><li><> represents <STDIN> </li></ul></ul></ul><ul><li>Note: Bind, Arrow and File operators will be explained later </li></ul>Linux User Group at San Jose State University
  15. 15. PERL – Standard Input <ul><li>Input operator </li></ul><ul><ul><li><STDIN> or <> </li></ul></ul><ul><ul><li>Read input from the user including ‘ ’ from the user </li></ul></ul><ul><ul><li>chomp operator can be used for removing the ‘ ’ character </li></ul></ul><ul><ul><li>By default input is stored in a default variable $_ </li></ul></ul><ul><li>chomp </li></ul><ul><ul><li>Usually used to discard the ‘ ’ character at the end of input string </li></ul></ul>Linux User Group at San Jose State University
  16. 16. PERL - Strings <ul><li>Sequence of characters, each character is an 8 bit value </li></ul><ul><li>Single quoted string </li></ul><ul><ul><li>Escape sequence except & ’ are not interpreted so </li></ul></ul><ul><li>Double quoted string </li></ul><ul><ul><li>All escape sequences are interpreted so </li></ul></ul><ul><li>Concatenation Operator </li></ul><ul><ul><li>‘ .’ can be used for concatenating string values </li></ul></ul><ul><li>Repetition Operator </li></ul><ul><ul><li>‘ x’ makes as many number of concatenated copies of string </li></ul></ul>Linux User Group at San Jose State University
  17. 17. PERL – String Functions <ul><li>Converting to lower case using – lc STRING </li></ul><ul><li>Converting to upper case using – uc STRING </li></ul><ul><li>Converting initial case to lower using – lcfirst STRING </li></ul><ul><li>Converting initial case to upper using – ucfirst STRING </li></ul><ul><li>Getting string length using – length (STRING) </li></ul><ul><ul><li>Returns the length of the string </li></ul></ul><ul><ul><li>If STRING is omitted, it returns the length of the string stored in $_ </li></ul></ul>Linux User Group at San Jose State University
  18. 18. PERL – String Functions contd <ul><li>Searching string using – index (STRING, SUBSTRING, [POSITION]) </li></ul><ul><ul><li>returns the index of the first occurrence of the SUBSTRING in STRING on or after POSITION </li></ul></ul><ul><ul><li>If POSITION is ignored, it starts searching from the first location </li></ul></ul><ul><ul><li>returns -1 if not found </li></ul></ul><ul><ul><li>rindex can be used to find the index of the last occurrence of the SUBSTRING in STRING on or before POSITION </li></ul></ul>Linux User Group at San Jose State University
  19. 19. PERL – String Functions contd <ul><li>Extracting/Replacing substring using – </li></ul><ul><li>substr STRING,OFFSET,[LENGTH], REPLACEMENT </li></ul><ul><ul><li>Extracts and returns the substring from OFFSET to LENGTH+OFFSET </li></ul></ul><ul><ul><li>If LENGTH is omitted, extraction starts from OFFSET to end of STRING </li></ul></ul><ul><ul><li>If LENGTH is negative, extraction omits that much number of characters from the end </li></ul></ul><ul><ul><li>If OFFSET is negative extraction starts from end of the string and moves back wards </li></ul></ul><ul><ul><li>If REPLACEMENT is specified, extracted substring will be replaced by REPLACEMENT </li></ul></ul>Linux User Group at San Jose State University
  20. 20. PERL – Control Structures <ul><li>Branching Statements </li></ul><ul><ul><li>if </li></ul></ul><ul><ul><li>if – else </li></ul></ul><ul><ul><li>if – elsif </li></ul></ul><ul><li>Looping Statements </li></ul><ul><ul><li>while / until </li></ul></ul><ul><ul><li>do – while/ until </li></ul></ul><ul><ul><li>for </li></ul></ul><ul><ul><li>foreach </li></ul></ul><ul><li>Miscellaneous Control Statements </li></ul><ul><ul><li>last, next, redo </li></ul></ul><ul><ul><li>Expression modifiers </li></ul></ul><ul><ul><li>exit, die </li></ul></ul>Linux User Group at San Jose State University
  21. 21. PERL – Control Structures contd <ul><ul><li>if statement </li></ul></ul><ul><ul><ul><li>if ( condition ) { </li></ul></ul></ul><ul><ul><ul><li>#True Block </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><li>If - else statement </li></ul></ul><ul><ul><ul><li>if( condition ) { </li></ul></ul></ul><ul><ul><ul><li>#True Block </li></ul></ul></ul><ul><ul><ul><li>}else { </li></ul></ul></ul><ul><ul><ul><li>#False Block </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><li>if – elsif statement </li></ul></ul><ul><ul><ul><li>If( condition1) { </li></ul></ul></ul><ul><ul><ul><li>#True block for Condition1 </li></ul></ul></ul><ul><ul><ul><li>}elsif(condition2) { </li></ul></ul></ul><ul><ul><ul><li>#True block for Condition2 </li></ul></ul></ul><ul><ul><ul><li>}else { </li></ul></ul></ul><ul><ul><ul><li>#False block </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul>Linux User Group at San Jose State University
  22. 22. PERL – Control Structures contd <ul><li>while loop </li></ul><ul><ul><ul><li>while (condition) { </li></ul></ul></ul><ul><ul><ul><li>#while block statements </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>Control comes out of the loop when the condition is FALSE </li></ul></ul></ul><ul><li>until loop </li></ul><ul><ul><ul><li>until (condition) { </li></ul></ul></ul><ul><ul><ul><li>#until block statements </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>Control comes out of the loop when the condition is TRUE </li></ul></ul></ul>Linux User Group at San Jose State University
  23. 23. PERL – Control Structures contd <ul><li>do while loop </li></ul><ul><ul><ul><li>do{ </li></ul></ul></ul><ul><ul><ul><li>#while block statements </li></ul></ul></ul><ul><ul><ul><li>}while (condition) </li></ul></ul></ul><ul><ul><ul><li>Control comes out of the loop when the condition is FALSE </li></ul></ul></ul><ul><li>do until loop </li></ul><ul><ul><ul><li>do { </li></ul></ul></ul><ul><ul><ul><li>#until block statements </li></ul></ul></ul><ul><ul><ul><li>}until (condition) </li></ul></ul></ul><ul><ul><ul><li>Control comes out of the loop when the condition is TRUE </li></ul></ul></ul>Linux User Group at San Jose State University
  24. 24. PERL – Control Structures contd <ul><li>for </li></ul><ul><ul><ul><li>for(init expr ; condition ; increment/decrement ) { </li></ul></ul></ul><ul><ul><ul><ul><li>#for block </li></ul></ul></ul></ul><ul><ul><ul><ul><li>} </li></ul></ul></ul></ul><ul><li>foreach </li></ul><ul><ul><li>mostly used when iteration has to be done for different values in a list </li></ul></ul><ul><ul><ul><li>foreach Variable (LIST) { </li></ul></ul></ul><ul><ul><ul><li>#Block of Statements </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul>Linux User Group at San Jose State University
  25. 25. PERL – Control Structures contd <ul><li>continue </li></ul><ul><ul><li>flow control statement follows while or foreach loop </li></ul></ul><ul><ul><li>continue block will be executed after every successful completion of an iteration </li></ul></ul><ul><li>next </li></ul><ul><ul><li>used to continue with the next iteration of the loop by stopping current iteration </li></ul></ul><ul><ul><li>cannot be used in side do-while/do-until loop </li></ul></ul><ul><ul><li>if continue block is present it will also be executed </li></ul></ul><ul><li>redo </li></ul><ul><ul><li>restarts the loop without evaluating the condition again </li></ul></ul><ul><ul><li>continue block is not executed, if present </li></ul></ul><ul><li>last </li></ul><ul><ul><li>exits the loop </li></ul></ul><ul><ul><li>continue block is not executed, if present </li></ul></ul>Linux User Group at San Jose State University
  26. 26. PERL – Control Structures contd <ul><li>exit </li></ul><ul><ul><li>used to terminate the execution of a script </li></ul></ul><ul><ul><li>exit 0 denotes exit on success and exit 1 denotes exit on error </li></ul></ul><ul><ul><li>cannot display error messages while exiting </li></ul></ul><ul><ul><li>$Choice=<STDIN> </li></ul></ul><ul><ul><li>if ($Choice==4) { exit 0}; </li></ul></ul><ul><li>die </li></ul><ul><ul><li>displays the error message to STDERR stream </li></ul></ul><ul><ul><li>and terminates the execution of a script </li></ul></ul><ul><ul><li>copy($TargetFile,$SourceFile) or die “File cannot be copied” </li></ul></ul>Linux User Group at San Jose State University
  27. 27. PERL - Arrays <ul><ul><li>Set of scalar values </li></ul></ul><ul><ul><li>Dynamically grows/shrinks when ever required </li></ul></ul><ul><ul><li>Can store dissimilar data types </li></ul></ul><ul><ul><li>Prefixed with ‘@’ symbol </li></ul></ul><ul><ul><li>Un-initialized locations and locations beyond the end of array will be undef </li></ul></ul><ul><ul><li>Can be initialized using </li></ul></ul><ul><ul><ul><li>List </li></ul></ul></ul><ul><ul><ul><li>qw operator </li></ul></ul></ul><ul><ul><ul><li>Repetition operator (X) </li></ul></ul></ul><ul><ul><ul><li>Range operator (..) </li></ul></ul></ul><ul><ul><ul><li>Individual locations </li></ul></ul></ul>Linux User Group at San Jose State University
  28. 28. PERL – Arrays contd <ul><li>Creation using Range operator </li></ul><ul><ul><li>@EmpNumber = (1001..1200) ; </li></ul></ul><ul><ul><li>- Can be used if array has to be initialized by a range of elements </li></ul></ul><ul><li>Creation using Repetition operator </li></ul><ul><ul><li>@Number = (0) X 10; </li></ul></ul><ul><ul><li>- Can be used if array has to be initialized by same value in all locations </li></ul></ul><ul><li>Creation of array with dissimilar elements </li></ul><ul><ul><li>@Details=(1001,”John”,3400.50); </li></ul></ul>Linux User Group at San Jose State University
  29. 29. PERL – Arrays contd <ul><li>Length of the array </li></ul><ul><ul><li>$#<array name> stores the last index of the array </li></ul></ul><ul><ul><li>$#<array name> +1 will give the number of elements </li></ul></ul><ul><li>Emptying an array </li></ul><ul><ul><ul><li>$#Emp = -1; </li></ul></ul></ul><ul><ul><ul><li>OR </li></ul></ul></ul><ul><ul><ul><li>@Emp = ( ); </li></ul></ul></ul><ul><ul><ul><li>OR </li></ul></ul></ul><ul><ul><ul><li>@Emp = undef; </li></ul></ul></ul><ul><li>Looping through an Array using foreach statement </li></ul><ul><li>converting scalar into an array using split function </li></ul><ul><li>Sorting an Array using – sort @<array_name> </li></ul><ul><li>Reversing an Array using – reverse @<array_name> </li></ul>Linux User Group at San Jose State University
  30. 30. PERL – Arrays contd <ul><li>Pushing and Popping elements </li></ul><ul><ul><li>push (<Array>, <Value>/<List>) </li></ul></ul><ul><ul><ul><li>Will add the element to the end of array </li></ul></ul></ul><ul><ul><ul><li>Array expands automatically </li></ul></ul></ul><ul><ul><li>pop (<Array>) </li></ul></ul><ul><ul><ul><li>Will remove the element from the end of the array </li></ul></ul></ul><ul><ul><ul><li>Array shrinks automatically </li></ul></ul></ul><ul><li>Shifting and Unshifting </li></ul><ul><ul><li>unshift (<Array>, <Value>/<List>) </li></ul></ul><ul><ul><ul><li>Will add the element/list to the front of the array & returns number of elements </li></ul></ul></ul><ul><ul><ul><li>Array expands automatically </li></ul></ul></ul><ul><ul><li>shift (<Array>) </li></ul></ul><ul><ul><ul><li>Will remove the element from front of the array </li></ul></ul></ul><ul><ul><ul><li>Array shrinks automatically </li></ul></ul></ul>Linux User Group at San Jose State University
  31. 31. PERL – Hashes <ul><li>Hashes </li></ul><ul><ul><li>Unordered collection of values </li></ul></ul><ul><ul><li>Each element is linked to a key, which uniquely identifies that element </li></ul></ul><ul><ul><li>Any element from the hash can be retrieved, added, deleted using the key </li></ul></ul><ul><ul><li>A hash variable is prefixed with % </li></ul></ul><ul><ul><li>Also called as associative arrays </li></ul></ul><ul><li>Accessing elements </li></ul><ul><ul><li>Elements can be retrieved using key </li></ul></ul><ul><ul><li>$RetrievedElement = $Hash{Key}; </li></ul></ul><ul><li>Adding new elements </li></ul><ul><ul><li>$Hash{ new key}= new element </li></ul></ul><ul><li>Changing the existing elements </li></ul><ul><ul><li>$Hash{key} = new element </li></ul></ul>Linux User Group at San Jose State University
  32. 32. PERL – Hashes contd <ul><li>Deleting key / value pairs </li></ul><ul><ul><li>delete ($Hash{Key}) </li></ul></ul><ul><li>Getting all keys or all values </li></ul><ul><ul><li>keys (%hash) </li></ul></ul><ul><ul><li>values (%hash) </li></ul></ul><ul><li>Does a key exist?? </li></ul><ul><ul><li>Using exists keyword </li></ul></ul><ul><li>Looping through hash elements </li></ul><ul><ul><li>using foreach and keys </li></ul></ul>Linux User Group at San Jose State University
  33. 33. Perl – more data structures <ul><li>Combination of arrays and hashes </li></ul><ul><li>Arrays of Arrays </li></ul><ul><li>Hashes of Arrays </li></ul><ul><li>Arrays of Hashes </li></ul><ul><li>Hashes of Hashes </li></ul><ul><li>and so on… </li></ul><ul><li>http://perldoc.perl.org/perldsc.html </li></ul>Linux User Group at San Jose State University
  34. 34. PERL – Regular Expressions <ul><li>A regular expression , often called a pattern in Perl, is a template that either matches or doesn't match a given string. </li></ul><ul><li>Using simple patterns: </li></ul><ul><ul><li>To compare a pattern (regular expression) to the contents of $_, simply put the pattern between a pair of forward slashes (/) </li></ul></ul><ul><li>$_ = “perl script&quot;; </li></ul><ul><li>if (/perl/) { </li></ul><ul><li> print &quot;It matched! &quot;; </li></ul><ul><li>} </li></ul><ul><li>Note: $_ is the default variable </li></ul>Linux User Group at San Jose State University
  35. 35. PERL – Regular Expression contd <ul><li>Metacharacters </li></ul><ul><ul><li>Dot (.) is a wildcard character - it matches any single character except a newline (which is represented by &quot; &quot;) </li></ul></ul><ul><ul><ul><li>/b.t/ will match bat, bet, bit, but etc. It will not match bt or boat etc. </li></ul></ul></ul><ul><ul><li>A backslash in front of any metacharacter makes it non-special. </li></ul></ul><ul><ul><ul><li>/3.14159/ doesn't have a wildcard character. </li></ul></ul></ul><ul><ul><li>Star (*) is a wildcard character – it matches the preceding character zero or more times </li></ul></ul><ul><ul><ul><li>/perl *script/ matches any number of tab characters between perl and script. i.e. it matches “perl script&quot; with one tab, or &quot;perl script&quot; with two tabs, or “perl script&quot; with three tabs, or even “perlscript&quot; with nothing in between at all. </li></ul></ul></ul>Linux User Group at San Jose State University
  36. 36. PERL – Regular Expression contd <ul><li>Metacharacters </li></ul><ul><ul><li>Plus (+) is to match the preceding character one or more times </li></ul></ul><ul><ul><ul><li> /perl +script/ matches if perl and script are separated only by spaces. This pattern won't match “perlscript”, since the plus matches only if there are one or more spaces between the two words. </li></ul></ul></ul><ul><ul><li>Question mark (&quot;?&quot;) means that the preceding character is optional </li></ul></ul><ul><ul><ul><li>/perl ? script/ matches it perl and script are separated by one space or no space. This will match “perl script” as well as “perlscript”. </li></ul></ul></ul><ul><ul><li>Parentheses (&quot;( )&quot;) may be used for grouping </li></ul></ul><ul><ul><li> /(perl)+/ matches strings like perlperlperl </li></ul></ul><ul><ul><li>The vertical bar (|), often pronounced &quot;or&quot; means that either the left side may match, or the right side </li></ul></ul><ul><ul><li> /unix|perl/ will match any string that mentions unix or perl </li></ul></ul>Linux User Group at San Jose State University
  37. 37. PERL – Regular Expression contd <ul><li>Character class </li></ul><ul><ul><li>a list of possible characters inside square brackets ([]), matches any single character from within the class. </li></ul></ul><ul><ul><ul><li>[abcwxyz] may match any one of the seven characters. </li></ul></ul></ul><ul><ul><ul><li>[a-zA-Z] may match any of the alphabets (both uppercase and lowercase). </li></ul></ul></ul><ul><ul><li>A caret (^) at the start of the character class negates it. </li></ul></ul><ul><ul><ul><li>[^def] will match any single character except “d”, “e” or “f”. </li></ul></ul></ul><ul><ul><li>[d] or [0-9] will match any digit </li></ul></ul><ul><ul><li>[w] is a shortcut for any &quot;word&quot; character: </li></ul></ul><ul><ul><ul><li>[w] or [A-Za-z0-9_] will match any “word” </li></ul></ul></ul><ul><ul><li>s is a shortcut for white space character </li></ul></ul>Linux User Group at San Jose State University
  38. 38. PERL – Regular Expression Contd <ul><li>Matches with m// </li></ul><ul><ul><li>m// (pattern match) operator allows you to choose any pair of delimiters to quote the contents </li></ul></ul><ul><ul><li>m(perl), m<perl>, m{perl}, or m[perl] </li></ul></ul><ul><li>Case Insensitive Matching with /i </li></ul><ul><ul><li>To make a case-insensitive pattern match, so that you can match PERL as easily as perl or Perl, use the /i modifier: </li></ul></ul><ul><li>Binding Operator =~ </li></ul><ul><ul><li>Matching against $_ is merely the default; the binding operator (=~) tells Perl to match the pattern on the right against the string on the left, instead of matching against $_ </li></ul></ul><ul><li>Substitution with s/// </li></ul><ul><ul><li>s/// is the search and replace feature. This simply replaces whatever part of a variable matches a pattern with a replacement string. </li></ul></ul><ul><ul><li>If the match fails, nothing happens, and the variable is untouched </li></ul></ul>Linux User Group at San Jose State University
  39. 39. PERL – Regular Expression Contd <ul><li>Global Replacements with /g </li></ul><ul><ul><li>s/// will make just one replacement, even if others are possible. The /g modifier tells s/// to make all possible replacements </li></ul></ul><ul><ul><li>A fairly common use of a global replacement is to collapse whitespace; that is, to turn any arbitrary whitespace into a single space </li></ul></ul>Linux User Group at San Jose State University
  40. 40. PERL - Subroutines <ul><li>Section of the script that performs a specific task </li></ul><ul><li>Values can be passed to subroutine so that it performs the task on these values </li></ul><ul><li>Values passed to the subroutines are called arguments </li></ul><ul><li>Return value is send back by the subroutine </li></ul><ul><li>@_ is an array where the argument values are stored during subroutine call </li></ul><ul><li>Subroutine definitions can be placed anywhere in your program text </li></ul>Linux User Group at San Jose State University
  41. 41. PERL – Subroutine contd <ul><li>Subroutine Declaration </li></ul><ul><ul><li>sub MySubroutine() </li></ul></ul><ul><ul><ul><li>MySubroutine accepts no arguments </li></ul></ul></ul><ul><ul><li>sub MySubroutine($) </li></ul></ul><ul><ul><ul><li>MySubroutine accepts one scalar argument </li></ul></ul></ul><ul><ul><li>sub MySubroutine($$) </li></ul></ul><ul><ul><ul><li>MySubroutine accepts 2 scalar arguments </li></ul></ul></ul><ul><ul><li>sub MySubroutine(@) </li></ul></ul><ul><ul><ul><li>MySubroutine accepts an array as an argument </li></ul></ul></ul><ul><ul><li>sub MySubroutine(%) </li></ul></ul><ul><ul><ul><li>MySubroutine accepts a hash reference as an argument </li></ul></ul></ul><ul><ul><li>sub MySubroutine($@) </li></ul></ul><ul><ul><ul><li>MySubroutine accepts a scalar value and an array as argument </li></ul></ul></ul><ul><ul><li>sub MySubroutine($;$) </li></ul></ul><ul><ul><ul><li>MySubroutine accepts 2 arguments, where the second argument is optional </li></ul></ul></ul>Linux User Group at San Jose State University
  42. 42. PERL – Subroutine contd <ul><li>Argument passing & Returning Values </li></ul><ul><ul><li>Arguments passed from the calling function are stored in an array @_ </li></ul></ul><ul><li>Default arguments </li></ul><ul><ul><li>Default arguments are specified in the prototype, separated by ‘;’ from mandatory parameters </li></ul></ul><ul><li>Scope of a variable </li></ul><ul><ul><li>Default scope of all variables are global </li></ul></ul><ul><ul><li>Scope can be changed by using ‘my’ or ‘local’ keyword </li></ul></ul><ul><li>Changing the scope of a variable using ‘my’ </li></ul><ul><ul><li>Restricts the scope of a variable to the block in which it is defined </li></ul></ul><ul><ul><li>It is not visible to the subroutine called from the enclosing block </li></ul></ul><ul><li>Changing the scope of a variable using ‘local’ </li></ul><ul><ul><li>Restricts the scope of a variable to the block in which it is defined </li></ul></ul><ul><ul><li>It is visible to the subroutine called from the enclosing block </li></ul></ul>Linux User Group at San Jose State University
  43. 43. PERL – Subroutine contd <ul><li>Reference Variable </li></ul><ul><ul><li>Reference variable store the reference (address) of the variables </li></ul></ul><ul><ul><li>Variables can be directly accessed using reference variables </li></ul></ul><ul><ul><li>Reference to a scalar </li></ul></ul><ul><li>Command line arguments </li></ul><ul><ul><li>Command line arguments are stored in a built in array @ARGV when a perl script is executed </li></ul></ul>Linux User Group at San Jose State University
  44. 44. PERL – File I/O <ul><li>Data that outlives the program </li></ul><ul><ul><li>needs to be stored </li></ul></ul><ul><ul><li>in a permanent storage </li></ul></ul><ul><ul><li>so that it can be referred later on </li></ul></ul><ul><li>Example </li></ul><ul><ul><li>word processing application might save the text in a linked list or some other data structure when the application is running, but when the application is terminated the contents of the linked list need to stored in a file </li></ul></ul>Linux User Group at San Jose State University
  45. 45. PERL – File I/O contd <ul><li>Opening a File </li></ul><ul><ul><li>open FILEHANDLE, FileName </li></ul></ul><ul><ul><li>Returns true (1) if successfully opened, false (0) otherwise </li></ul></ul><ul><ul><ul><li>open (MyFileHandle,”MyData.txt”) </li></ul></ul></ul><ul><ul><li>File will be opened for input if file name is prefixed by ‘<‘ </li></ul></ul><ul><ul><ul><li>open (MyFileHandle,”<MyData.txt”) </li></ul></ul></ul><ul><ul><li>File will be opened for output if the file name is prefixed by ‘>’ </li></ul></ul><ul><ul><ul><li>If the file exists contents will be erased </li></ul></ul></ul><ul><ul><ul><li>If the file doesn’t exists new file will be created </li></ul></ul></ul><ul><ul><ul><li>open (MyFileHandle,”>MyData.txt”) </li></ul></ul></ul><ul><ul><li>File will be opened for appending if the the file name is prefixed by ‘>>’ </li></ul></ul><ul><ul><ul><li>If the file doesn’t exist new file will be created </li></ul></ul></ul><ul><ul><ul><li>open (MyFileHandle,”>>MyData.txt”) </li></ul></ul></ul>Linux User Group at San Jose State University
  46. 46. PERL – File I/O contd <ul><li>Opening a File contd </li></ul><ul><ul><li>File will be opened for read & write if the file name is prefixed by ‘+>’ or ‘+<‘ </li></ul></ul><ul><ul><ul><li>‘ +>’ will erase the existing contents and open the file for read and write </li></ul></ul></ul><ul><ul><ul><li>‘ +<‘ must be used if the file has to be opened for updating the existing contents </li></ul></ul></ul><ul><ul><ul><li>open (MyFileHandle, “+<MyData.txt”) </li></ul></ul></ul><ul><li>Handling Errors in File Open </li></ul><ul><ul><li>An alternate statement can be attached to the open statement using ‘or’ </li></ul></ul><ul><ul><li>The alternate statement will be executed if opening a file fails </li></ul></ul><ul><ul><ul><li>open FileHandle,FileName or {Alternate Statement} </li></ul></ul></ul><ul><li>Closing a File </li></ul><ul><ul><li>Closing a file will transfer the un buffered data to the file </li></ul></ul><ul><ul><li>Returns true(1) if successful, false(0) otherwise </li></ul></ul><ul><ul><ul><li>close FileHandle </li></ul></ul></ul>Linux User Group at San Jose State University
  47. 47. PERL – File I/O contd <ul><li>Reading from a File using <> (angle) operator </li></ul><ul><ul><li><FileHandle> returns the next line of input from the file </li></ul></ul><ul><ul><li>If <> alone is specified, input is taken from STDIN </li></ul></ul><ul><ul><li>Returns null when end of file is reached </li></ul></ul><ul><li>Reading from file using readline </li></ul><ul><ul><li>readline (FileHandle) returns one line of data from the file </li></ul></ul><ul><ul><li>Undefined value will be returned if end of file is reached </li></ul></ul><ul><li>Read from file using getc </li></ul><ul><ul><li>getc(FileHandle) returns a character from the file </li></ul></ul><ul><ul><li>Undefined value will be returned if end of file is reached </li></ul></ul><ul><li>Writing unformatted records into a file using print </li></ul><ul><ul><li>print FileHandle Message </li></ul></ul><ul><ul><ul><li>Returns true if successful, false otherwise </li></ul></ul></ul><ul><ul><li>print FIleHandle Message or Alternate statement </li></ul></ul><ul><ul><ul><li>Returns false and executes alternate statement if unsuccessful, true otherwise </li></ul></ul></ul>Linux User Group at San Jose State University
  48. 48. Questions Linux User Group at San Jose State University

×