Ashish Kumar Jha Brief Perl Tutorial

Embed Size (px)

Citation preview

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    1/136

    8/12/2009

    Agenda

    Perl Basics Data Types Operators Control Structures

    Lists Hashes Sub Routines

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    2/136

    Practical Extraction & Reporting Language Perl is a High-level Scripting language Faster than sh or csh, slower than C More powerful than C, and easier to use No need for sed, awk, head, wc, tr, Compiles at run-time Available for Unix, Linux, Mac etc. Best Regular Expressions on Earth

    What is Perl?

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    3/136

    Whats Perl Good For?

    Quick scripts, complex scripts Parsing & restructuring data files CGI-BIN scripts High-level programming

    o Networking librarieso Graphics librarieso Database interface libraries

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    4/136

    Whats Perl Bad For?

    Compute-intensive applications (use C) Hardware interfacing (device drivers)

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    5/136

    Installation for Unix / Windows

    Unix Windows

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    6/136

    Perl Basics

    Leading spaces on a line are ignored Statements are terminated with a semicolon. Anything after a hash sign (#) is ignored

    except in strings. A string is basically a series of characters

    enclosed in quotes Spaces, tabs, and blank lines outside of

    strings are irrelevant-one space is as good asa hundred.

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    7/136

    8/12/2009

    File Naming Schemeo filename.pl (programs)o filename.pm (modules collection of useful perlsubroutines)

    o filename.ph (old Perl 4 header file)

    Should call exit() function whenfinishedo Exit value of zero means success

    exit (0); # successfulo Exit value non-zero means failure exit (2); # failure

    Perl Basics

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    8/136

    8/12/2009

    Invoking perl from cmd-line

    o perl -w (-w to give all warnings)o print hello world \n;o __END__

    Output : hello world

    Perl Helpo man perlo perldoc perlfunc (perl built-in functions)

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    9/136

    8/12/2009

    Data Types

    Integer literalo 25 750000 1_000_000_000o 8#100 16#FFFF0000

    Floating Point literalo 1.25 50.0 6.02e23 -1.6E-8

    String literalo hi therehi there,$nameo print Text Utility, version $ver\n;o Use double quote for special charinterpretation

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    10/136

    8/12/2009

    Data Types

    Booleano 0 0.0 represents False o all other values represents True

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    11/136

    8/12/2009

    Numericand String Literals

    Numbers - This is the most basic data type. Strings - A string is a series of characters

    that are handled as one unit.Arrays - An array is a series of numbers and

    strings handled as a unit.Associative Arrays - This is the most

    complicated data type.

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    12/136

    8/12/2009

    Special Esc Sequence chars

    \n,\r, \t, \a, \b, \x are also availableo \l Lowercase next lettero \L Lowercase all following letters until \Eo \u Uppercase next lettero \U Uppercase all following until \E

    o \Q Backslash-quote all nonalphanumerics until\Eo \E Terminate \L , \U, or \Q

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    13/136

    8/12/2009

    Operators

    Math(operator prcedeces are as in C)o The usual suspects: + - * /

    $total = $subtotal * (1 + $tax / 100.0);

    o Exponentiation: ** $cube = $value ** 3;$cuberoot = $value ** (1.0/3);

    o Bit-level Operations left-shift: $val = $bits >> 8;

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    14/136

    8/12/2009

    Operators

    Assignmentso As usual: = += -= *= /= **= =

    $value *= 5; $longword

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    15/136

    8/12/2009

    Operators

    Boolean (against bits in each byte)o Usual operators: & |o Exclusive-or: ^o Bitwise Negation: ~

    $picture = $backgnd & ~$mask | $image;

    Boolean Assignmento &= |= ^=

    $picture &= $mask;

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    16/136

    8/12/2009

    Operators

    Logical (expressions)o && And operatoro | | Or operatoro ! Not operatoro AND And, low precedenceo OR Or, low precedenceo NOT Not, low precedenceo XOR Exclusive or, low precedence

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    17/136

    8/12/2009

    Operators

    o Short Circuit Operators expr1 && expr2

    expr1 is evaluated. expr2 is only evaluated if expr1 was true.

    expr1 || expr2

    expr1 is evaluated. expr2 is only evaluated if expr1 was false.

    Examples open () || die couldnt open file; $debug && print users name is $name\n;

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    18/136

    8/12/2009

    Operators

    Modulo: %o $a = 123 % 10; ($a is 3)

    Multiplier: xo print ride on the , choo-x2, train;(prints ride on the choo-choo-train)

    o $stars = * x 80;

    Assignment: %= x=

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    19/136

    8/12/2009

    Operators

    String Concatenation: . .=o $name = Uncle . $space . Sam;o $cost = 34.99;

    o $price = Hope Diamond, now only \$;o $price .= $cost;

    String Repetition Operator xo "fred" x 3 # is "fredfredfred"

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    20/136

    8/12/2009

    Conditionals Operators

    numeric string Equal: == eq Not Equal != ne Less/Greater Than: < > lt gt Less/Greater or equal: = le ge Zero and empty-string means False All other values equate to True

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    21/136

    8/12/2009

    numeric string Comparison: cmp

    o Results in a value of -1, 0, or 1 Logical Not: !

    Grouping: ( )

    Conditionals Operators

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    22/136

    8/12/2009

    Scalar Variables

    Scalaro $num = 14;o $fullname = Cass A. Nova;o Variable Names are Case Sensitiveo Variable name length is limited to 255

    charso Underlines Allowed: $Program_Version =1.0;

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    23/136

    8/12/2009

    chop and chomp functions

    chop function (any last char in the string isremoved)o $x = "hello world";o chop($x); # $x is now "hello worl"

    chomp function (only newline char removed)o $a = "hello world\n";o chomp ($a); # $a is now "hello world"o chomp ($a); # aha! no change in $ao @stuff = ("hello\n","world\n","happy days");o chomp(@stuff); # @stuff is now ("hello","world","happy

    days")

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    24/136

    8/12/2009

    Reading values from keyboard

    o $a = ; # get the texto chomp($a); # get rid of that pesky newlineo A common abbreviation for these two lines is:

    o chomp($a = );o @a = ; # read standard input in a listcontext

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    25/136

    8/12/2009

    undef value

    What happens if you use a scalar variablebefore you give it a value?

    Nothing serious, and definitely nothingfatal

    Variables have the undef value before they

    are first assigned This value looks like a zero when used as anumber, or the zero-length empty string whenused as a string

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    26/136

    8/12/2009

    Control Structures

    if statement - first styleo if ($porridge_temp < 40) {print too hot.\n;}elsif ($porridge_temp > 150) {

    print too cold.\n;}else {print just right\n;}

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    27/136

    8/12/2009

    Control Structures

    if statement - second styleo statement if condition;

    print \$index is $index if $DEBUG;

    o Single statements onlyo Simple expressions only

    unless is a reverse ifo statement unless condition;

    print millenium is here! unless $year < 2000;

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    28/136

    8/12/2009

    Control Structures

    for loop - first styleo for (initial; condition; increment) { code }

    for ($i=0; $i

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    29/136

    8/12/2009

    Control Structures

    for loop with default loop variable for (@employees) {print $_ is an employee\n;print; # this prints $_}

    Foreach and For are actually the same.

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    30/136

    8/12/2009

    while

    loopo while (condition) { code }

    $cars = 7;while ($cars > 0) {print cars left: , $cars--, \n;}

    while ($game_not_over) {}

    Control Structures

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    31/136

    8/12/2009

    until loop is opposite of whileo until (condition) { code }

    $cars = 7;until ($cars

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    32/136

    8/12/2009

    Bottom-check Loopso do { code } while (condition);o do { code } until (condition);

    $value = 0;do {

    printEnter Value:

    ;$value = ;

    } until ($value > 0);

    Control Structures

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    33/136

    8/12/2009

    Loop Controlso next operator - go on to next iterationo redo operator - re-runs current iterationo last operator - ends the loop immediately

    o while (cond) {next if $a < 5;}

    o You can break out of multilevel loops usinglabels (not covered in this presentation)

    Control Structures

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    34/136

    8/12/2009

    o Break out of multilevel loops using labels top: while (condition) {for ($car in @cars) {do stuffnext top if situation;}}

    Control Structures

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    35/136

    8/12/2009

    Loop Controls Exampleo while ($qty = &get_quantities) {last if $qty < 0; # denotes the endnext if $qty % 2; # skip evenquantities

    $total += $qty;$qtycnt++;}print Average of Odd Quantities: ,$total/$qtycnt, \n;

    Control Structures

    N S i h S ?!?

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    36/136

    8/12/2009

    No Switch Statement?!?

    Perl needs no Switch (Case) statement. Use if/else combinations instead

    o if (cond1) { }elsif (cond2) { }elsifelse

    This will be optimized at compile time

    Li V i bl

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    37/136

    8/12/2009

    List Variables

    List (one-dimensional array) A list is ordered scalar data The smallest array has no elements, while thelargest array can fill all of availablememory

    List literalo (1,2,3) # array of three values 1, 2, and 3o ("fred",4.5) # two values, "fred" and 4.5

    Li V i bl

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    38/136

    8/12/2009

    List Variables

    o List constructor operator (1 .. 5) # same as (1, 2, 3, 4, 5) (1.2 .. 5.2) # same as (1.2, 2.2, 3.2, 4.2, 5.2)

    o @memory = (16, 32, 48, 64);o @people = (Alice, Alex, Albert);o First element numbered 0 (can be changed)

    o Single elements are scalar: $names[0] = Ferd;o Slices are ranges of elements @guys = @people[1..2];

    o How big is my list? print Number of people: $#people\n;

    Li t V i bl

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    39/136

    8/12/2009

    List Variables

    List with lots of wordso @a = ("fred","barney","betty","wilma");o Alternative

    @a = qw(fred barney betty wilma); # better! qw quoted words

    Printing the whole listo print("The answer is ",@a,"\n");

    Converting into scalaro ($a,$b,$c) = (1,2,3);o ($a,$b) = ($b,$a); # swap $a and $b

    Li t V i bl

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    40/136

    8/12/2009

    List Variables

    Removing an element in listo ($e,@fred) = @fred; # remove first element of @fred

    Getting first elemento ($a) = @fred; # $a gets first element

    As an array element access

    o @fred = (7,8,9);o $b= $fred[0];#give7to$b(firstelementof @fred)o $fred[0] = 5; # now @fred = (5,8,9)o $fred[2]++;# increment third element of @fred

    List Variables

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    41/136

    8/12/2009

    List Variables

    Sliceso @fred[0,1]; # same as ($fred[0],$fred[1])o @who = (qw(fred barney betty wilma))[2,3];

    Assigning values beyond array subsrcipto @fred = (1,2,3);o $fred[3] = "hi"; # @fred is now (1,2,3,"hi")o $fred[6] = "ho";

    # @fred is (1,2,3,"hi",undef,undef,"ho")

    o Use $#fred to get the index value of the lastelement of @fred

    o A -ve subscript on an array counts back fromend

    Push and Pop functions

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    42/136

    8/12/2009

    Push and Pop functions

    The push and pop functions do things to the"right" side of a listo push(@mylist,$newvalue); # like @mylist =(@mylist,$newvalue) first argument must be an array variable name

    o @mylist = (1,2,3);

    o push(@mylist,4,5,6); # @mylist =(1,2,3,4,5,6)

    o $oldvalue = pop(@mylist); # removes thelast element of @mylist The pop function returns undef if given an empty list

    Shift and unshift functions

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    43/136

    8/12/2009

    Shift and unshift functions

    unshift and shift functions perform the corresponding actions

    on the "left" side of a listo unshift(@fred,$a); # like @fred = ($a,@fred);o unshift(@fred,$a,$b,$c); # like @fred = ($a,$b,$c,@fred);o $x = shift(@fred); # like ($x,@fred) = @fred;o shift returns undef if given an empty array variableo @fred = (5,6,7);

    o unshift(@fred,2,3,4); # @fred is now (2,3,4,5,6,7)o $x = shift(@fred); # $x gets 2, @fred is now (3,4,5,6,7)

    Reverse and Sort functions

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    44/136

    8/12/2009

    Reverse and Sort functions

    reverse functiono @a = (7,8,9);o @b = reverse(@a); # gives @b the value of (9,8,7)o @b = reverse(7,8,9); # same thing

    Sort functiono @x = sort("small","medium","large");o # @x gets "large","medium","small"o @y = (1,2,4,8,16,32,64);o @y = sort(@y); # @y gets 1,16,2,32,4,64,8

    Hash Variables

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    45/136

    8/12/2009

    Hash Variables

    Hash (associative array) Hash is like an array whose index values areany arbitrary scalars

    The elements of a hash have no particular order A hash variable name is a percent sign (%)

    followed by a letter, followed by zero or moreletters, digits, and underscores

    Hash Variables

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    46/136

    8/12/2009

    Hash Variables

    o $fred{"aaa"} = "bbb"; # creates key "aaa", value "bbb"o $fred{234.5} = 456.7; # creates key "234.5", value 456.7o %var = { name => paul, age => 33 };o Single elements are scalar

    print $var{name}; $var{age}++;

    o How many elements are in my hash? @allkeys = keys(%var); $num = $#allkeys;

    Hash Variables

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    47/136

    8/12/2009

    Hash Variables

    The keys functiono yields a list of all the current keys in the hash

    $fred{"aaa"} = "bbb"; $fred{234.5} = 456.7; @list = keys(%fred); # @list gets ("aaa",234.5) or # (234.5,"aaa")

    foreach $key (keys (%fred)) { # once for each key of %fred

    print "at $key we have $fred{$key}\n"; # show key and value

    }

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    48/136

    Hash Variables

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    49/136

    8/12/2009

    The value functiono The values(%hashname) function returns a list of allthe current values of the %hashname %lastname = (); # force %lastname empty $lastname{"fred"} = "flintstone"; $lastname{"barney"} = "rubble"; @lastnames = values(%lastname); # grab the values At this point @lastnames contains either ("flintstone", "rubble")or ("rubble", "flintstone").

    Hash Variables

    Hash Variables

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    50/136

    8/12/2009

    Hash Variables

    The each functiono On each evaluation of this function for the same hash,the next successive key-value pair is returned untilall the elements have been accessed

    o Step thru each key value pairs

    while (($first,$last) = each(%lastname)) { print "The last name of $first is $last\n"; }

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    51/136

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    52/136

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    53/136

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    54/136

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    55/136

    Subroutines (Functions)

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    56/136

    8/12/2009

    Passing Argumentso Passes the valueo Lists are expanded

    @a = (5,10,15);@b = (20,25);

    &mysub(@a,@b); this passes five arguments: 5,10,15,20,25 mysub can receive them as 5 scalars, or one array

    Subroutines (Functions)

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    57/136

    8/12/2009

    Noteso Recursion is legalo local is the Perl 4 version of my

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    58/136

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    59/136

    Special Variables

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    60/136

    8/12/2009

    $0 name of the program running $/ input record separator (\n) $\ output record separator (none) $, output field separator for print(none) $ Array Elements separator $. input line number

    Special Variables

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    61/136

    8/12/2009

    $[ first element index number (0) $! system error message (related to $ERRNOvariable)

    $$ Perl Process ID $^O Operating Systems name

    Special Variables

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    62/136

    8/12/2009

    @_ list of all the arguments @INC library directories (require, use) @ARGV command line args list %ENV Environment variables

    File Functions

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    63/136

    Much faster than system()o unlink file; - deletes a fileo rename oldfile, newfile;o rmdir directory;o link existingfile, newfile;

    o symlink existingfile, newfile;o chmod 0644, file1, file2, ;o chown $uid, $gid, @filelist;

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    64/136

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    65/136

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    66/136

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    67/136

    Basic File I/O

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    68/136

    How does work?o opens each ARGV filename forreading

    o if no ARGVs, reads from stdino great for writing filters, heres

    cat: while () {print; # same as print $_;}

    Basic File I/O

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    69/136

    Reading from a Pipeo open (FILEHANDLE, ps aux |) || die\ launch of ps failed: $!;while () {chop;print $_\n;}close FILEHANDLE;

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    70/136

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    71/136

    Pattern Matching

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    72/136

    A pattern is a sequence ofcharacters to be searched for ina character string

    o syntax:string

    =~pattern

    o Returns true if it matches, falseif not.

    o Example: match abc anywhere instring: if ($str =~ /abc/) { }

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    73/136

    Pattern Matching

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    74/136

    \b and \B Word boundary pattern Anchors /d[^eE]f/ Exclude Character [] Character-Range Escape Sequences \d Any digit [0-9] \D Anything other than a digit [^0-9] \w Any word character [_0-9a-zA-Z] \W Anything not a word character [^_0-9a-zA-Z] \s White space [ \r\t\n\f] \S Anything other than white space [^ \r\t\n\f]

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    75/136

    Substitution Operator

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    76/136

    Syntax : s/pattern/replacement/ $name =~ s/ASU/Arizona State University/; s/abc// s/[abc]+/0/

    Options for the SubstitutionOperator

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    77/136

    p

    g Change all occurrences of the pattern i Ignore case in pattern e Evaluate replacement string as expression m Treat string to be matched as multiple

    lines o Evaluate only once s Treat string to be matched as single line x Ignore white space in pattern

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    78/136

    Perl versus Unix Utilities

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    79/136

    sed - substitutionso sed: s/xxx/yyy/go vi: :%s/xxx/yyy/go perl: s/xxx/yyy/g;

    tr - translationso tr: tr [A-Z][a-z](platformdependent)

    o perl: tr/A-Z/a-z/; (platformindependent)

    Perl versus Unix Utilities

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    80/136

    wc - char / word / line countingo wc: wc -l < filenameo perl: perl -ne END{print $.\n} "value1",..}; $anon_hash_copy = { %hash};

    To dereference a hash reference: %hash= %$href; $value = $href->{$key};

    @slice=@$href{$key1,$key2}#no arrow!@keys = keys %$href;

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    89/136

    References to Functions

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    90/136

    8/12/2009

    To get a code reference: $cref =\&func;$cref = sub { ... }; To call a code reference:@returned = $cref->(@arguments);

    @returned = &$cref(@arguments);

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    91/136

    Packages

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    92/136

    8/12/2009

    Collect data & functions in a separate(private) namespace

    Similar to static functions & data in C Perl 4 concept, works in Perl 5 too Reusable code

    require or use

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    93/136

    8/12/2009

    The require or use statements both pulla module into your program Require loads modules at runtime,useloads modules at compile-time

    The required file extension for a Perl

    module is ".pm". use NET::SSH;

    Packages

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    94/136

    8/12/2009

    To find the current package:$this_pack = __PACKAGE__; To find the caller's package:$that_pack = caller();

    Automating Module Clean-Up

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    95/136

    8/12/2009

    For set-up code, put executable statements outside

    subroutine definitions in the module file For clean-up code, use an END subroutine in that

    module. END { logmsg("shutdown");close(LF) or die "close

    $Logfile failed: $!";}

    Preparing a Module for Distribution

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    96/136

    8/12/2009

    Use h2xs -XA -n Command to generate ownmodules

    Use the make dist directive to bundleit all up into a tar archive for easy

    distribution.

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    97/136

    Reporting Errors and Warnings Like Built-Ins

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    98/136

    8/12/2009

    To print the errors that are there inour modules .

    Use Carp ;

    Building and Installing a CPAN Module

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    99/136

    8/12/2009

    % gunzip Some-Module-4.54.tar.gz% tar xf Some-Module-4.54% cd Some-Module-4.54% perl Makefile.PL% make

    % make test% make install

    Characteristics of OOP

    Data encapsulation concept Reusability

    ddi f di h i

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    100/136

    8/12/2009

    Extensibility:adding new features or responding to changing

    operating environments can be solved by introducing a fewnew objects and modifying some existing ones;

    Maintainability: objects can be maintained separately,making locating and fixing problems easier;

    OOPS in PERL A class is a Perl package. This package for a classprovides the methods for objects.

    Amethodis simply a Perl subroutine. The only catch withwriting such methods is that the name of the class is thefirst argument

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    101/136

    8/12/2009

    first argument.

    An object in Perl is simply a reference to some data itemwithin the class. Perl provides abless() function which is used to return a

    reference and which becomes an object.

    OOPS in PERL Defining a Class :package Person; To create an object we need an object constructor . The object reference is created by blessing a reference to

    the package's class .

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    102/136

    8/12/2009

    the package s class .

    sub new{my $class = shift;my $self = {};bless $self, $class;return $self;}

    OOPS in PERL

    E d fi th d i

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    103/136

    8/12/2009

    Even we can define our own methods inPERL .

    sub getFirstName {return $self->{_firstName};}

    Inheritance in PERL

    Acquiring the properties of one class

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    104/136

    8/12/2009

    Acquiring the properties of one classto another class .

    Use @ISA for implementing inheritancein perl .

    Searching for a method is in the order:

    @ISA array , AUTOLOAD subroutine

    AUTOLOAD subroutine

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    105/136

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    106/136

    Debugging in Perl

    Debug mode: perl -d filename [args]

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    107/136

    8/12/2009

    Debug mode: perl d filename [args]o Display Commands

    h Extended help h h Abbreviated help

    l (lowercase-L) list lines of code l sub list subroutine sub l 5 list line 5 l 3-6 list lines 3 through 6 inclusive l list next window of lines

    Debugging in Perl

    o Display Commands (continued)

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    108/136

    8/12/2009

    o Display Commands (continued)

    w watch point /pat search forwards for patternpat(regular expressions legal)

    ?pat search backwards for patternpat(regular expressions legal)

    S list all subroutines w/ packages

    Debugging in Perl

    o Display Commands (continued)

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    109/136

    8/12/2009

    p y ( )

    - (hyphen) list previous window p exprprints Perl expression expr = aliasvalue set a command alias H [-num] history (list previous cmds) commandexecute any Perl commandor line of code you want

    q quit

    Debugging in Perl

    o Stepping & Tracing

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    110/136

    8/12/2009

    pp g g

    s step -- execute 1 line of code. Steps oversubroutines.

    n next -- execute 1 line of code.Steps into subroutines.

    r return from function

    Debugging in Perl

    o Breakpoints

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    111/136

    8/12/2009

    b line set a breakpoint at line line b sub set a breakpoint at subroutine sub d line delete breakpoint D delete all breakpoints c [line] continue running until next breakpt[set a temporary breakpoint at line]

    L List all breakpoints

    Debugging in Perl

    o Actions

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    112/136

    8/12/2009

    a linecmdexecutes perl code cmdeach time line is reached

    A delete all line actions < cmdset action right before thedebugging prompt

    > cmdset action right after the

    debugging prompt

    Debugging in Perl

    How to Learn More

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    113/136

    8/12/2009

    o man perldebugo just try it!

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    114/136

    CGI Programming

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    115/136

    8/12/2009

    "CGI" stands for "Common Gateway Interface." CGI is a standard for interfacing external

    applications with information servers, such as HTTPor Web servers .

    CGI program is executable . A CGI program can be written in any programming

    language, but Perl is one of the most popular,

    CGI Programming

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    116/136

    8/12/2009

    CGI Programming

    Steps To Create a CGI Program :

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    117/136

    8/12/2009

    File should be created in the cgi-bin/directory until unless we configure the webserver .

    File should have execute permissions . First line should be perl interpreter

    Next line should be print "Content-type:text/html\n\n";

    CGI Programming

    To avoid entering multiple print

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    118/136

    8/12/2009

    statements :print

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    119/136

    8/12/2009

    library . use CGI qw(:standard); header; start_html; end_html;

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    120/136

    CGI.pm Module

    GET Method

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    121/136

    8/12/2009

    Param Post Sendmail

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    122/136

    Parsing XML documents

    XML::Simple class exposes two methods,

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    123/136

    8/12/2009

    XMLin() and XMLout() . The XMLin() method reads an XML file orstring and converts it to a Perlrepresentation .

    XMLout() method does the reverse, readinga Perl structure and returning it as anXML document instance .

    Controlling parser behaviour

    The ForceArray option is a Boolean flag

    i

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    124/136

    8/12/2009

    that tells XML::Simple to turn XMLelements into regular indexed arraysinstead of hashes .

    KeyAttr, which can be used to tell

    XML::Simple to use a particular elementas a unique "key" when building the hashrepresentation of an XML document.

    Database Connection

    The DBI is a database access module for

    h l i l

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    125/136

    8/12/2009

    the Perl programming language.

    Notation and Conventions

    $dbh Database handle object

    $ th St t t h dl bj t

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    126/136

    8/12/2009

    $sth Statement handle object$drh Driver handle object$rows Number of rows processed (ifavailable, else -1)$fh A filehandle

    undef NULL values are represented byundefined values in Perl\%attr Reference to a hash of attributevalues passed to methods

    Database Connection

    Connect :

    $dbh DBI > t($d $

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    127/136

    8/12/2009

    $dbh = DBI->connect($dsn, $user,$password, { RaiseError => 1, AutoCommit=> 0 }); Prepare :

    $sth = $dbh->prepare("SELECT * fromtable");

    Available Drivers

    DBD P PP P t SQL d i f th DBI

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    128/136

    8/12/2009

    Gofer

    DBD::PgPP PostgreSQL driver for the DBIDBD::mysql MySQL driver for the DBIDBD::SQLite Self Contained RDBMS in a DBIDBD::ODBC ODBC Driver for perl DBI

    Creating a Process

    Eval : eval (string);

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    129/136

    8/12/2009

    Eval : eval (string);system : system(list);fork : procid = fork();pipe : pipe (infile, outfile);exec : exec(list);

    Terminating a Process

    Die : die (message);

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    130/136

    8/12/2009

    Die : die (message);warn : warn (message);exit : exit (retcode);kill : kill (signal, proclist);

    Execution Control Functions

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    131/136

    8/12/2009

    sleep : sleep (time);wait : procid = wait();waitpid : waitpid (procid, waitflag);

    Signals Signals are a kind of notification delivered bythe operating system .

    To Print list of signals available :

    perl -e 'print join(" " keys %SIG) "\n"'

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    132/136

    8/12/2009

    perl e print join( , keys %SIG), \n$SIG{QUIT} = \&got_sig_quit; # call &got_sig_quit for every SIGQUIT$SIG{PIPE} = 'got_sig_pipe'; # call main::got_sig_pipe for every SIGPIPE$SIG{INT} = sub { $ouch++ }; # increment $ouch for every SIGINT$SIG{INT} = 'IGNORE'; # ignore the signal INT$SIG{STOP} = 'DEFAULT'; # restore default STOP signal handling

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    133/136

    IO::Socket

    It very hard to write each function

    The module IO::Socket provides an easy

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    134/136

    8/12/2009

    The module IO::Socket provides an easyway to create sockets which can then beused like file handles

    perldoc IO::Socket

    Socket Programming

    Net::Ping ModuleN t T l t M d l

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    135/136

    8/12/2009

    Net::Ping Module Net::Telnet Module Net::FTP Module Net::SSH::Perl Module

  • 7/31/2019 Ashish Kumar Jha Brief Perl Tutorial

    136/136