Practical Approach to PERL      Rakesh Mukundan
Scripting Language    Uses an interpreter to run the code    No compilation needed, just run it!    Interpreted line by...
PERL• Practical Extraction and Report Language• Also known as Practically Everything  Really Likeable• Began as the result...
Why Learn Perl•   Perl is easy and it makes life easy!•   Its open source•   Lots of tested modules available for re-use• ...
Do You Have Perl Installed?• Execute the following command in a shell  –   perl -v
Installation• UNIX and Linux : Available with installation CD or  standard repositories if not installed by default• Windo...
Your First Perl Program• Open MyFirstProgram.pl from the examples directory  with your favorite text editor ( gedit,vim,no...
Under the hood         Location of interpreter                Comment             A perl statement             terminated ...
Variables• Place to store data• A scalar variable stores a single value• Perl scalar names are prefixed with a dollar  sig...
Examples of Variables•   $floating_val   =   3.14•   $integer_val    =   1008•   $string_val     =   “My String”•   $hashR...
Numerical OperationsAddition : $var1 + $var2Subtraction : $var1 - $var2Multiplication: $var1 * $var2Division: $var1 / ...
Contd..    Greater than: $var1 > $var2    Greater than or equal: $var1 >= $var2    Less than : $var1 < $var2    Less t...
StringsAn string of characters, no size limit     “Hello World”Can be specified using single quotes() or double quotes(...
StringsAn string of characters, no size limit     “Hello World”Can be specified using single quotes() or double quotes(...
Special CharactersL Transform all letters to lowercasel Transform the next letter to lowercaseU Transform all letters t...
Print FunctionMost commonly used perl functionCan print a variable or string to console/file/any file handleUsage print...
User Input    <STDIN> stands for standard input    Program waits for user to enter an input    It will contain newline ...
Calculator ProgramAsk user to enter two numbersDo all the numerical operations mentioned in previous slide and print the...
String Operationsindex(STR,SUBSTR) :Returns the position of the first occurrence of SUBSTR in STRlength(EXPR) :Returns t...
Array• List of scalars• Similar to arrays in C,C++ etc..• Array is identified by @ symbol  • @FirstArray = (“one”,”two”,”t...
Arrays
Visualizing Data In Perl    Use the Dumper module   use Data::Dumper;    print Dumper $ref;    $ref is the refference ...
Working With Arrays• An array element can be indexed as  $MyFirstArray[1]• push() - adds an element to the end of an  arra...
A phonebook•   Pallava     => 3001•   Krishna     => 3002•   Godhavari   => 3003•   Kaveri      => 3004• How do you repres...
Hashes• Hash is a like a phone book which has names  and corresponding phone numbers• Each element in a hash will have a k...
Hashes
Working With Hash Values• Each value can be accessed by its key   – $Phonebook{“pallava”}• To add a new value to hash tabl...
Contd..• Checking if a particular key has already added in the  hash table   – if (exists($Phonebook{"pallava"}))   –{   –}
Program Control•   If•   While•   For•   Foreach
if•    Conditional statement to check if a criteria is    met or not•    The syntax is       •           if(condtion){ cod...
ifelse    Else is the compliment of if    Execute code if the condition is not met    Syntax                     if(co...
elsifif(condition1){     Code to execute}elsif(condition2){    Code to execute}Else{     Code to execute}
while•    Loop while the condition is true•    while($count<5){     •         Print “Cont:$countn”;     •         $count++...
for•    A for loop counts through a range of    numbers, running a block of code    each time it iterates through the loop...
foreach•    Used for iterating over an array or hash•    foreach(@MyArray){        •            print “Element : $_n”;•    }
Phonebook Program    Print existing numbers    Option to add a new entry    Option to delete and entry    Option to ex...
Strict UsageBy default perl doesnt need any variable to be declared before useSimple spelling mistakes in variable names...
Upcoming SlideShare
Loading in...5
×

Practical approach to perl day1

512

Published on

Learn perl with examples
www.rakeshmukundan.in

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
512
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
15
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Practical approach to perl day1

  1. 1. Practical Approach to PERL Rakesh Mukundan
  2. 2. Scripting Language Uses an interpreter to run the code No compilation needed, just run it! Interpreted line by line Fast to learn and program Easy debugging Every user is a developer :)
  3. 3. PERL• Practical Extraction and Report Language• Also known as Practically Everything Really Likeable• Began as the result of one mans frustration and, by his own account, inordinate laziness • Perl is free. The full source code and documentation are free to copy, compile, print, and give away
  4. 4. Why Learn Perl• Perl is easy and it makes life easy!• Its open source• Lots of tested modules available for re-use• You are too lazy to do mechanical repetitive work 
  5. 5. Do You Have Perl Installed?• Execute the following command in a shell – perl -v
  6. 6. Installation• UNIX and Linux : Available with installation CD or standard repositories if not installed by default• Windows : Many flavors are available with and without IDEs, free and proprietary etc – Active State Perl – Strawberry Perl
  7. 7. Your First Perl Program• Open MyFirstProgram.pl from the examples directory with your favorite text editor ( gedit,vim,notepad++ etc )• To run the program open up a shell and navigate to the examples directory • perl MyFirstProgram.pl• In Linux systems perl file can be directly executed, provided path to interpreter has been specified correctly. • chmod a+x MyFirstProgram.pl • ./MyFirstProgram.pl
  8. 8. Under the hood Location of interpreter Comment A perl statement terminated with a semi-colon
  9. 9. Variables• Place to store data• A scalar variable stores a single value• Perl scalar names are prefixed with a dollar sign ($) – Ex: $name,$password,$ip_address• No need to define a variable explicitly, use directly• A scalar can hold data of any type, be it a string, a number, or whatnot
  10. 10. Examples of Variables• $floating_val = 3.14• $integer_val = 1008• $string_val = “My String”• $hashReff = %HashToPoint;• $SubReff = MyRoutine();• $ScalarReff = $floating_val;
  11. 11. Numerical OperationsAddition : $var1 + $var2Subtraction : $var1 - $var2Multiplication: $var1 * $var2Division: $var1 / $var2Increment: $var++Power: $var1 ** $var2Modulus: $var1 % $var2;
  12. 12. Contd.. Greater than: $var1 > $var2 Greater than or equal: $var1 >= $var2 Less than : $var1 < $var2 Less than or equal: $var1<= $var2 Equality: $var1== $var2
  13. 13. StringsAn string of characters, no size limit  “Hello World”Can be specified using single quotes() or double quotes(“)Strings can be concatenated using dot (.) operatorNo operations are possible inside a single quoted string  “1 plus 2 is $value”  1 plus 2 is $value
  14. 14. StringsAn string of characters, no size limit  “Hello World”Can be specified using single quotes() or double quotes(“)Strings can be concatenated using dot (.) operatorNo operations are possible inside a single quoted string  “1 plus 2 is $value”  1 plus 2 is $value
  15. 15. Special CharactersL Transform all letters to lowercasel Transform the next letter to lowercaseU Transform all letters to uppercaseu Transform the next letter to uppercasen Begin on a new liner Apply a carriage returnt Apply a tab to the stringEEnds U, L functions
  16. 16. Print FunctionMost commonly used perl functionCan print a variable or string to console/file/any file handleUsage print <file handle> expressionBy default prints to STDOUT  Print “Hello World n”;  Print $MyVariable;  Print “My name is $MyVariable n”;  Print “One plus one is always 1+1 n”;
  17. 17. User Input <STDIN> stands for standard input Program waits for user to enter an input It will contain newline character also $MyAge= <STDIN>; chomp($MyAge);
  18. 18. Calculator ProgramAsk user to enter two numbersDo all the numerical operations mentioned in previous slide and print the output
  19. 19. String Operationsindex(STR,SUBSTR) :Returns the position of the first occurrence of SUBSTR in STRlength(EXPR) :Returns the length in characters of the value of EXPRrindex(STR,SUBSTR) :Works just like index except that it returns the position of the LAST occurrence of SUBSTR in STRsubstr(EXPR,OFFSET,LEN):Extracts a sub string out of EXPR and returns it
  20. 20. Array• List of scalars• Similar to arrays in C,C++ etc..• Array is identified by @ symbol • @FirstArray = (“one”,”two”,”three”);• Each element can be accessed by its corresponding index • print $FirstArray[2];
  21. 21. Arrays
  22. 22. Visualizing Data In Perl Use the Dumper module use Data::Dumper; print Dumper $ref; $ref is the refference to the variable print Dumper @Array; print Dumper %Hash;
  23. 23. Working With Arrays• An array element can be indexed as $MyFirstArray[1]• push() - adds an element to the end of an array.• unshift() - adds an element to the beginning of an array.• pop() - removes the last element of an array.• shift() - removes the first element of an array.
  24. 24. A phonebook• Pallava => 3001• Krishna => 3002• Godhavari => 3003• Kaveri => 3004• How do you represent such a list? – Lookup by names?
  25. 25. Hashes• Hash is a like a phone book which has names and corresponding phone numbers• Each element in a hash will have a key and value• For example – %PhoneBook = ( • “pallava” => 3001, • “krishna” => 3002, • “godhavari”=> 3003, • “kaveri” => 3004);
  26. 26. Hashes
  27. 27. Working With Hash Values• Each value can be accessed by its key – $Phonebook{“pallava”}• To add a new value to hash table – $Phonebook{“nilgiris”} =”3005”;• To delete a value from hash table – delete($Phonebook{“nilgiris”});• Looping through a hashtable – while (($key, $value) = each(%Phonebook)){ – Print $key.$value; –}
  28. 28. Contd..• Checking if a particular key has already added in the hash table – if (exists($Phonebook{"pallava"})) –{ –}
  29. 29. Program Control• If• While• For• Foreach
  30. 30. if• Conditional statement to check if a criteria is met or not• The syntax is • if(condtion){ code to execute;} • if($var1 ==5){ • print “variable is 5n”; • }
  31. 31. ifelse Else is the compliment of if Execute code if the condition is not met Syntax  if(condition){ code for condition met}  else{ code for condition false} if($var1==5){  print “variable value is 5n”; } else{  Print “variable value is not 5n”; }
  32. 32. elsifif(condition1){ Code to execute}elsif(condition2){ Code to execute}Else{ Code to execute}
  33. 33. while• Loop while the condition is true• while($count<5){ • Print “Cont:$countn”; • $count++;• }• While(1) makes an infinite loop• Flow Control • next :go to the next iteration • last:end while loop
  34. 34. for• A for loop counts through a range of numbers, running a block of code each time it iterates through the loop• for(initial, condition, $increment) { code to execute }• for($count=0;$count<11;$count++) { • Print “Count $count n”;• }
  35. 35. foreach• Used for iterating over an array or hash• foreach(@MyArray){ • print “Element : $_n”;• }
  36. 36. Phonebook Program Print existing numbers Option to add a new entry Option to delete and entry Option to exit the program Option to search by name
  37. 37. Strict UsageBy default perl doesnt need any variable to be declared before useSimple spelling mistakes in variable names can lead to hours of code debugging!By using the strict method,perl will strictly ask you declare variable  my $MyFirstVar;  my @MyFirstArray;  my %MyFirstHash;
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×