• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Basic perl programming
 

Basic perl programming

on

  • 208 views

Basic Perl programming for newbie

Basic Perl programming for newbie

Statistics

Views

Total Views
208
Views on SlideShare
208
Embed Views
0

Actions

Likes
0
Downloads
5
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Download Eclipse: http://www.eclipse.org/downloads/ Download ActivePerl 5.14.2: http://www.activestate.com/activeperl/downloads

Basic perl programming Basic perl programming Presentation Transcript

  • Basic Perl programming
  • Agenda  Perl introduction  Variables  Control Structures  Loops  Defining and using subroutines  Regular Expression  Using Boolean (True/False)  File handling August 2, 2012 2
  • Perl Introduction• Perl is a general-purpose programming language originally developed for text manipulation. Now, Perl used for web development, system administration, network programming, core generation and more.• Open Source and free licencing.• Support both procedural and OOP.• Excellent text handling and regular expressions August 2, 2012 3
  • Installation Perl• Install ActivePerl 5.14.2• Install Eclispse 3.6 or greater• In Eclipse IDE go to menu item “Help > Install New Software…” to install EPIC plugins of Perl at link: http://e-p-i-c.sf.net/updates/testing• After finish installed Perl plugins, go to menu “Run -> External Tools -> External Tools... “ to add and active the configuration for running Perl August 2, 2012 4
  • VariablesScalar: $myString = “Hello” ;  hello $num1 = 10.5;  10.5 $num2 = $num1;  10.5 print “Number is :$num1”;  Number is :10.5 Prefix characters on Perl: • $: variable containing scalar values such as a number or a string • @: variable containing a list with numeric keys • %: variable containing a list with strings as keys • &: subroutine • *: matches all structures with the associated name August 2, 2012 5
  • VariablesArray (1): @colors = (“Red”, “Blue”, “Orange”); $colors[0] = “Red”; $colors[1] = “Blue”; $colors[2] = “Orange”; print “Our colors variable contains: @ colors ”;  Our colors variable contains : Red Blue Orange print “First element of the colors is: $colors[0]”;  First element of the colors is: Red @CombinedArray =(@Array1,@Array2);// merge 2 arrays @hundrednums = (101 .. 200); August 2, 2012 6
  • VariablesArray (2): Perl functions for working with arrays: • pop - remove last element of an array: • push - add an element to the end of array; • shift - removes first element of an array; • unshift - add an element to the beginning of array; • sort - sort an array. EG: @colors = (“Red”, “Blue”, “Orange”); print “Our colors variable contains: @ colors ”;  Our colors variable contains : Red Blue Orange pop @colors; print “Colors after applying pop function: @array1[0..$#array1]";  Colors after applying pop function: Red Blue August 2, 2012 7
  • VariablesHashes:- %name_email = ("John", "john@example.com" , "George", "george@example.com");- %name_email = ( “John” => "john@example.com", “George” => "george@example.com", );Common used of Hash:- Print => print $name_email {"John"};- Delete => delete $name_email {"John"}; August 2, 2012 8
  • Control Structures - Conditional• IF: if (cond-expr 1) {…} elsif (cond-expr 2) {…} else {…} $num = 30; if ($num% 2 == 1) { print "an odd number."; } elsif ($num == 0) { print "zero."; } else { print "an even number."; } => an even number. August 2, 2012 9
  • Loops• For: for ([init-expr]; [cond-expr]; [loop-expr]) {…} for ($i = 1; $i < 10; $i++) { print "$i "; } => 1 2 3 4 5 6 7 8 9• While: while (cond-expr) {…} $var1 = 1; $var2 = 8; while ($var1 < $var2) { => 1 2 3 4 5 6 7 print "$var1 "; $var1 += 1; } August 2, 2012 10
  • Loops• Until: until (cond-expr) {…} $var1 = 1;$var2 = 8; until ($var2 < $var1) { print "$var2 "; $var2 -= 1; } => 8 7 6 5 4 3 2 1 August 2, 2012 11
  • Loops• foreach: – foreach[$loopvar] (list) {…} $searchfor = "Schubert"; @composers = ("Mozart", "Tchaikovsky", "Beethoven", "Dvorak", "Bach", "Handel", "Haydn", "Brahms", "Schubert", "Chopin"); foreach $name (@composers) { if ($name eq $searchfor) { print "$searchfor is found!n"; last; } } => Schubert is found! August 2, 2012 12
  • Defining and using subroutines$var1 = 100;$var2 = 200;$result = 0;$result = my_sum();print "$resultn";sub my_sum { $tmp = $var1 + $var2; return $tmp;}=> 300 August 2, 2012 13
  • Regular ExpressionPerl Regular Expressions are a strong point of Perl:• b: word boundaries • *: zero or more times• d: digits • +: one or more times• n: newline • ?: zero or one time• r: carriage return • {p,q}: at least p times and at most q times• s: white space characters • {p,}: at least p times• t: tab • {p}: exactly p times• w: alphanumeric characters• ^: beginning of string• $: end of string• Dot (.): any character• [bdkp]: characters b, d, k and p• [a-f]: characters a to f• [^a-f]: all characters except a to f• abc|def: string abc or string def• [:alpha:],[:punct:],[:digit:], … - use inside character class e.g., [[:alpha:]] August 2, 2012 14
  • Regular Expression : substitutions• The “s/<partten>/<replace_partten>/” substitution operator does the ‘search and replace’ - append a g to the operator to replace every occurrence. - append an i to the operator, to have the search case insensitive Examples: $line = “He is out with Barney. He is really happy!”; $line =~ s/Barney/Fred/; #He is out with Fred. He is really happy! $line =~ s/Barney/Wilma/;#He is out with Fred. He is really happy! (nothing happens as search failed) $line = “He is out with Fred. He is really happy” $line =~ s/He/She/g; #She is out with Fred. She is really happy! $text =~ s/bug/feature/g; # replace all occurrences of "bug" August 2, 2012 15
  • Regular Expression : translations• The "tr/<partten> /<replace_partten>/" operator performs a substitution on the individual characters. Examples: $x =~ tr/a/b/; # Replace each "a" with "b". $x =~ tr/ /_/; # Convert spaces to underlines. $x =~ tr/aeiou/AEIOU/; # Capitalise vowels. $x =~ tr/0-9/QERTYUIOPX/; # Digits to letters. $x =~ tr/A-Z/a-z/; # Convert to lowercase. August 2, 2012 16
  • Regular Expression : matching• The “m//” (or in short //) operator checks for matching . Examples: $x =~ m/dd/; # Search 2 digits. $x =~ m/^This/; # Search string begin with “This”. $x =~ m/string$/; # Search string end with “This” . $x =~ m /sds/; # Search a digit with white space in front and after it $x =~ m/^$/; # Search for blank line. August 2, 2012 17
  • Regular Expression : split & join• Split breaks up a string according to a separator. $line = “abc:def:g:h”; @fields = split(/:/,$line) => #(‘abc’,’def’,’g’,h’)• Join glues together a bunch of pieces to make a string. @fields = (‘abc’,’def’,’g’,h’) $new_line = join(“:”,@fields) => #“abc:def:g:h” August 2, 2012 18
  • Boolean : True / False ? Expression 1 0.0 a string 0 empty str undefif( $var ) true true true false false falseif( defined $var ) true true true true true falseif( $var eq ) false false false false true trueif( $var == 0 ) false true true true true true August 2, 2012 19
  • Logical Tests: AND, OR• AND Value of B Value of A 1 0.0 B string 0 empty str undef 1 1 0.0 B string 0 empty str undef 0.0 1 0.0 B string 0 empty str undef A string 1 0.0 B string 0 empty str undef 0 0 0 0 0 0 0 empty str empty str empty str empty str empty str empty str empty str undef undef undef undef undef undef undef August 2, 2012 20
  • Logical Tests: AND, OR• OR Value of B Value of empty 1 0.0 B string 0 undef A str 1 1 1 1 1 1 1 0.0 0.0 0.0 0.0 0.0 0.0 0.0 A string A string A string A string A string A string A string 0 1 0.0 B string 0 empty str undef empty 1 0.0 B string 0 empty str undef str undef 1 0.0 B string 0 empty str undef August 2, 2012 21
  • Exclusive OR: XOR• XOR Value of B Value of empty 1 0.0 a string 0 undef A str 1 false false false true true true 0.0 false false false true true true a string false false false true true true 0 true true true false false false empty true true true false false false str undef true true true false false false August 2, 2012 22
  • File handling• Opening a File: open (SRC, “my_file.txt”);• Reading from a File $line = <SRC>; # reads upto a newline character• Closing a File close (SRC); August 2, 2012 23
  • File handling• Opening a file for output: open (DST, “>my_file.txt”);• Opening a file for appending open (DST, “>>my_file.txt”);• Writing to a file: print DST “Printing my first line.n”;• Safeguarding against opening a non existent file open (SRC, “file.txt”) || die “Could not open file.n”; August 2, 2012 24
  • File Test Operators• Check to see if a file exists: if ( -e “file.txt”) { # The file exists! }• Other file test operators: -r readable -x executable -d is a directory -T is a text file August 2, 2012 25
  • File handling sample• Program to copy a file to a destination file #!/usr/bin/perl -w open(SRC, “file.txt”) || die “Could not open source file.n”; open(DST, “>newfile.txt”); while ( $line = <SRC> ) { print DST $line; } close SRC; close DST; August 2, 2012 26
  • August 2, 2012 27