introduction to perl 2009

Upload: prashant-singh

Post on 06-Apr-2018

224 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Introduction to Perl 2009

    1/109

    2008 McAfee, Inc.

    Introduction to Perl

    Theres More Than One Way to Do It

    MIC Automation Club

  • 8/3/2019 Introduction to Perl 2009

    2/109

    Confidential McAfee Internal Use Only

    Agenda

    Day-1Introduction to Perl

    Variables

    Operators

    Array and Hash Functions

    Conditions and Loop Operators

    Day-2

    Subroutines

    File Operations and IO

    Regular Expressions

    Perl Built in functions

    Day-3

    Test

    2/22/20122

  • 8/3/2019 Introduction to Perl 2009

    3/109

    Confidential McAfee Internal Use Only

    Programming Methodologies

    Structured or Method based C

    Perl

    Object Oriented

    C++ Perl

    Event Based

    C#

    VB

    2/22/20123

  • 8/3/2019 Introduction to Perl 2009

    4/109

    What is Perl ?

  • 8/3/2019 Introduction to Perl 2009

    5/109

    Confidential McAfee Internal Use Only

    What is Perl ?

    Perl stands forPracticalExtraction andReportingLanguage.

    Created in 1987 by Larry Wall.

    Inspired from Unix like languages like Sed, Awk and Shell Script.

    Most Perl Modules and scripts are platform independent.

    C-Like syntax.

    Perl is a freeware and open source.

    2/22/20125

  • 8/3/2019 Introduction to Perl 2009

    6/109

    Confidential McAfee Internal Use Only

    Slogan!!

    The Perl slogan isThere's more than one way to do it

    2/22/20126

  • 8/3/2019 Introduction to Perl 2009

    7/109

    How Do I Install and Run Perl?

  • 8/3/2019 Introduction to Perl 2009

    8/109

    Confidential McAfee Internal Use Only

    How Do I Install and Run Perl?

    Perl is available athttp://www.activestate.com/Products/ActivePerl/Download.html .

    Command to execute a Perl program

    For e.g. if Helloworld.pl is a Perl script

    Perl Helloworld.pl

    2/22/20128

  • 8/3/2019 Introduction to Perl 2009

    9/109

    Variables and Data types

    $scalar

    @array

    %hash

  • 8/3/2019 Introduction to Perl 2009

    10/109

    Confidential McAfee Internal Use Only

    Variables

    Variables are storage containers for numbers, strings, and compoundstructures.

    Perl supports three types of variables:

    Scalars

    Arrays

    Hashes

    A variable name can be up to 255 characters.

    A variable name cannot start with a number

    e.g. $64bitint (leading numbers not legal)

    2/22/201210

  • 8/3/2019 Introduction to Perl 2009

    11/109

    Confidential McAfee Internal Use Only

    Variables (contd..)

    A minus sign is not legal in the variable namee.g. $file-handle (minus sign not legal)

    Variable name cannot have special characters other thanunderscore(_)

    e.g. $excangerateto (pound symbol not legal)

    Here are some valid scalar variable names:

    $A_Scalar_Variable

    $scalarNo8

    $_private_scalar

    2/22/201211

  • 8/3/2019 Introduction to Perl 2009

    12/109

    Scalars ($)

  • 8/3/2019 Introduction to Perl 2009

    13/109

    Confidential McAfee Internal Use Only

    Scalars

    Scalar variables store a single value. They are prefixed with a $.

    Consider this example:

    $counter

    $string=Hello world;

    $string=HelloWorld;

    $string=123;

    $string=123.456;

    2/22/201213

  • 8/3/2019 Introduction to Perl 2009

    14/109

    Arrays (@)

  • 8/3/2019 Introduction to Perl 2009

    15/109

    Confidential McAfee Internal Use Only

    Arrays

    An array is an indexed list of values with a consistent order.

    Names of arrays are prefixed with @.

    Examples of Arrays

    @first_array = (1, 2, 3, 4);

    @second_array = ('one', '2', 'three', '4', '5');

    @a = qw(fred barney betty wilma);

    2/22/201215

  • 8/3/2019 Introduction to Perl 2009

    16/109

    Hashes (%)

  • 8/3/2019 Introduction to Perl 2009

    17/109

    Confidential McAfee Internal Use Only

    Hashes

    Hashes are tables of key-value pairs.

    They are also called associative arrays.

    For example:

    %hash = ('Mouse', 'Jerry', 'Cat', 'Tom', 'Dog', 'Spike');

    2/22/201217

  • 8/3/2019 Introduction to Perl 2009

    18/109

    Arrays and Hash Functions

  • 8/3/2019 Introduction to Perl 2009

    19/109

    Confidential McAfee Internal Use Only

    Arrays and Hash Functions

    ValuesGrabs the values from the hash

    @values = values(%hash);

    Keys

    Returns a list consisting of all the keys of the named hash.@keys = keys %hash;

    The keys are returned in an apparently random order, but it is thesame order as either the values().

    2/22/201219

  • 8/3/2019 Introduction to Perl 2009

    20/109

    Confidential McAfee Internal Use Only

    Arrays and Hash Functions

    shiftshift ARRAY

    Shifts the first value of the array off and returns it, shortening the arrayby 1 and moving everything down. If there are no elements in thearray, returns the undefined value.

    push

    push ARRAY,LIST

    Treats ARRAY as a stack, and pushes the values of LIST onto the endof ARRAY. The length of ARRAY increases by the length of LIST.Returns the number of elements in the array following the completedpush.

    2/22/201220

  • 8/3/2019 Introduction to Perl 2009

    21/109

    Confidential McAfee Internal Use Only

    Arrays and Hash Functions

    popARRAYPops and returns the last value of the array, shortening the array byone element. If there are no elements in the array, returns theundefined value .

    2/22/201221

  • 8/3/2019 Introduction to Perl 2009

    22/109

    Confidential McAfee Internal Use Only

    Arrays and Hash Functions

    deletedelete LIST

    Deletes the specified keys and associated values from ahash, or the specified elements from an array. The operationworks on individual elements or slices.

    For example:

    delete $array[0];

    Also note that when deleting an array item, only the itemsvalue is emptied; it doesnt remove the item from the list or

    close the gap between the preceding and subsequent item(s).

    2/22/201222

  • 8/3/2019 Introduction to Perl 2009

    23/109

    Confidential McAfee Internal Use Only

    Arrays and Hash Functions

    eacheach HASH

    In a list context, returns a two-element list referring to thekey and value for the next element of a hash, allowing you

    to iterate over it. In a scalar context, returns only the key forthe next element in the hash. Information is returned in arandom order.

    2/22/201223

  • 8/3/2019 Introduction to Perl 2009

    24/109

    Confidential McAfee Internal Use Only

    Arrays and Hash Functions

    existsexists EXPR

    Returns true if the specified hash key exists,regardless of the corresponding value, even if its

    undef.

    Returns in Scalar Context

    0 if hash element or array index does not exist and1 if hash element or array index exists.

    2/22/201224

  • 8/3/2019 Introduction to Perl 2009

    25/109

    Confidential McAfee Internal Use Only

    Arrays and Hash Functions

    joinjoin EXPR, LIST

    Combines the elements ofLIST into a single string using thevalue ofEXPR to separate each element. It is effectively theopposite ofsplit. Note that EXPR is only interpolate between

    pairs of elements in LIST; it will not be placed either beforethe first or after the last element in the string. To jointogether strings without a separator, supply an empty stringrather than undef.

    2/22/201225

  • 8/3/2019 Introduction to Perl 2009

    26/109

    Confidential McAfee Internal Use Only

    Arrays and Hash Functions

    reversereverse LIST

    In a list context, returns the elements ofLIST in reverseorder. In a scalar context, returns a concatenated string of thevalues ofLIST, with all bytes in opposite order.

    Returns in Scalar Context Returns in List Context

    String List

    2/22/201226

  • 8/3/2019 Introduction to Perl 2009

    27/109

    Confidential McAfee Internal Use Only

    Arrays and Hash Functions

    scalarscalar EXPR

    Forces the evaluation ofEXPR to be in scalar context, even ifit would normally work in list context

    2/22/201227

  • 8/3/2019 Introduction to Perl 2009

    28/109

    Confidential McAfee Internal Use Only

    Arrays and Hash Functions

    splicesplice ARRAY, OFFSET, LENGTH, LIST

    splice ARRAY, OFFSET, LENGTH

    splice ARRAY, OFFSET

    Removes the elements ofARRAY from the element

    OFFSET forLENGTH elements, replacing the elementsremoved with LIST, if specified. IfLENGTH is omitted,removes everything from OFFSET onwards.

    2/22/201228

  • 8/3/2019 Introduction to Perl 2009

    29/109

    Confidential McAfee Internal Use Only

    List and Scalar Context

    Every Perl expression is in one of two `contexts', either `list context' or`scalar context', depending on whether it is expected to produce a listor a scalar.

    Example of list context:

    ($a,$b,$c)=(1,2,3);@arr=(4,5,6);

    Example of scalar context:

    $a=@arr;

    $a=GetDate();

  • 8/3/2019 Introduction to Perl 2009

    30/109

    Operators

  • 8/3/2019 Introduction to Perl 2009

    31/109

    Confidential McAfee Internal Use Only

    Operators

    Basic arithmetic and logical operators

    Assignment operator =

    Arithmetic operators +-*/%**

    Logical operators && || ! and or not Increment and decrement operators ++ --

    Comparison operators == != < >= eq ne lt legt ge cmp

    2/22/201231

  • 8/3/2019 Introduction to Perl 2009

    32/109

    Conditional Statements

  • 8/3/2019 Introduction to Perl 2009

    33/109

    Confidential McAfee Internal Use Only

    Conditional Statements

    Simple If

    If else

    Nested If else

    else if ladder

    unless

    2/22/201233

  • 8/3/2019 Introduction to Perl 2009

    34/109

    Confidential McAfee Internal Use Only

    Conditional Statements (contd..)

    Simple if

    if (EXPRESSION)

    {

    Statements;}

    2/22/201234

  • 8/3/2019 Introduction to Perl 2009

    35/109

    Confidential McAfee Internal Use Only

    Conditional Statements (contd..)

    The if-else condition

    if (EXPRESSION)

    {

    Statements;

    }

    else

    {

    Statements;

    }

    2/22/201235

  • 8/3/2019 Introduction to Perl 2009

    36/109

    Confidential McAfee Internal Use Only

    Conditional Statements (contd..)

    Nested if-else condition

    if (EXPRESSION)

    {if (EXPRESSION)

    {

    Statements;

    }

    else

    {

    Statements;

    }

    }

    else

    {Statements;

    }

    2/22/201236

  • 8/3/2019 Introduction to Perl 2009

    37/109

    Confidential McAfee Internal Use Only

    Conditional Statements (contd..)

    else if ladder

    if (EXPRESSION)

    {Statements;

    }

    elsif (EXPRESSION)

    {

    Statements;

    }

    elsif (EXPRESSION)

    {

    Statements;

    }

    else{

    Statements;

    }

    2/22/201237

  • 8/3/2019 Introduction to Perl 2009

    38/109

    Confidential McAfee Internal Use Only

    Conditional Statements (contd..)

    Other forms of if statement

    BLOCK if EXPRESSION;

    STATEMENT if EXPRESSION;

    STATEMENT, STATEMENT, STATEMENT if EXPRESSION;

    2/22/201238

  • 8/3/2019 Introduction to Perl 2009

    39/109

    Confidential McAfee Internal Use Only

    Conditional Statements (contd..)

    Unless statementunless(Expression)

    {

    Statements;

    }

    Unlike the if statement, the code block is executed only if theexpression is false rather than true.

    2/22/201239

  • 8/3/2019 Introduction to Perl 2009

    40/109

    Loops

  • 8/3/2019 Introduction to Perl 2009

    41/109

    Confidential McAfee Internal Use Only

    Loops

    While Loop

    while ()

    {

    Statements;

    }

    While loop executes as long as the expression is true and

    once the expression is false, control exits the loop

    2/22/201241

  • 8/3/2019 Introduction to Perl 2009

    42/109

    Confidential McAfee Internal Use Only

    Loops (contd..)

    Do While Loop

    do{

    Statements;

    } while (expression);

    do- while loop executes as long as the expression is true

    and once the expression is false, control exits the loop.

    Unlike while loop, do-while loop is executed at least once

    irrespective of the truthness or falsity of the expression.

    2/22/201242

  • 8/3/2019 Introduction to Perl 2009

    43/109

    Confidential McAfee Internal Use Only

    Loops ( contd..)

    Until Loop

    until (EXPRESSION)

    {

    Statements;

    }

    until loop executes as long as the value of the expression is

    false and exits the loop when the value becomes true.

    2/22/201243

  • 8/3/2019 Introduction to Perl 2009

    44/109

    Confidential McAfee Internal Use Only

    Loops (contd..)

    For LoopPerl's for control structure is like the common for control

    structure

    you may have seen in other languages such as C. It looks

    like this:

    for (initialization; check; increment)

    {

    body;

    }

    2/22/201244

  • 8/3/2019 Introduction to Perl 2009

    45/109

    Confidential McAfee Internal Use Only

    Loops (contd..)

    foreach Loopforeach loop is same as for loop but does not require initialization andincrement as part of the declaration of the loop.

    @array=(1,2,3,4);

    foreach(@array)

    {print This is element $_\n;

    }

    2/22/201245

  • 8/3/2019 Introduction to Perl 2009

    46/109

    Loop controls

  • 8/3/2019 Introduction to Perl 2009

    47/109

    Confidential McAfee Internal Use Only

    Loop controls

    The last Operator

    The last operator immediately ends the execution of theloop. (If you've used the "break" operator in C or a similarlanguage, it's like that.) It's the "emergency exit" for loop blocks.

    Example:

    for ($i=0;$i

  • 8/3/2019 Introduction to Perl 2009

    48/109

    Confidential McAfee Internal Use Only

    Loop controls (contd..)

    The next OperatorThe next control continues with the next iteration of the

    loop (much like the "continue" operator in C or a similarlanguage):

    Example:

    for($i=0;$i < 10;$i++){

    if($i == 5)

    {

    next; #This will not print the value of $i and will goto the

    #next value in the loop 6} print $i\n;

    }

    2/22/201248

  • 8/3/2019 Introduction to Perl 2009

    49/109

    Confidential McAfee Internal Use Only

    Loop controls (contd..)

    The redo Operator

    The third member of the loop control triad is redo. Itsays to go back to the top of the current loop block, withouttesting any conditional expression or advancing to the nextiteration.

    for($i=0;$i < 10;$i++)

    ####Redo comes here{

    if($i == 5)

    {

    $i++;

    redo; # This will execute the loop again if $i==5.

    }print $i\n;

    }

    2/22/201249

  • 8/3/2019 Introduction to Perl 2009

    50/109

    Subroutines

  • 8/3/2019 Introduction to Perl 2009

    51/109

    Confidential McAfee Internal Use Only

    Subroutines

    Defining a subroutine

    use the keyword sub, followed by the name of your subroutine,followed by a code block

    sub Hello{

    print Hello andWelcome to this world of Perl\n;

    }

    2/22/201251

  • 8/3/2019 Introduction to Perl 2009

    52/109

    Confidential McAfee Internal Use Only

    Subroutines (contd..)

    Passing arguments to subroutines

    When arguments are passed to a subroutine they are stored inthe default variable @_.

    Getting the arguments directly from the @_ array

    sub Add

    {

    return $_[0] + $_[1];

    }

    Saving the arguments list into another set of variables or anotherarray

    sub Add{

    my ($num1,$num2)=@_;

    return $num1+$num2;

    }

    2/22/201252

  • 8/3/2019 Introduction to Perl 2009

    53/109

    Confidential McAfee Internal Use Only

    Subroutines (contd..)

    Using the Shift operator to get the arguments.

    sub Add

    {

    my $num1=shift;

    my $num2=shift;return $num1+$num2;

    }

    2/22/201253

  • 8/3/2019 Introduction to Perl 2009

    54/109

    Confidential McAfee Internal Use Only

    Subroutines (contd..)

    Passing Lists to Subroutines. Because the @_ variable is an array, it can be used to supply lists

    to a Subroutine.

    All three of the following are valid:

    @args = (2,3);

    mysub(1,@args);@args = (1,2,3);

    mysub(@args);

    More than one list cannot be passed to a subroutine without using

    References.

    2/22/201254

  • 8/3/2019 Introduction to Perl 2009

    55/109

    Confidential McAfee Internal Use Only

    Subroutines (contd..)

    The fundamental rule to remember is that when passing arrays orlists to subroutines you can pass only one array or list, and it mustbe the last argument supplied.

    sub process {

    my ($first, $second, @rest) = @_;

    }

    If you try to extract the array as the first element, then it willimmediately gobble up all of@_, even if there are arguments afterthe array leaving any scalar entries empty.

    sub process {

    my (@rest, $first, $second) = @_;

    }

    2/22/201255

  • 8/3/2019 Introduction to Perl 2009

    56/109

    Confidential McAfee Internal Use Only

    Subroutines (contd..)

    Passing Hashes to Subroutines When you supply a hash to a subroutine, the hash is automatically

    translated into a list of key/value pairs

    For E.g.

    sub display_hash

    {my (%hash) = @_;

    foreach (keys %hash)

    {

    print "$_ => $hash{$_}\n";

    }

    }

    2/22/201256

  • 8/3/2019 Introduction to Perl 2009

    57/109

    Confidential McAfee Internal Use Only

    Subroutines (contd..)

    The fundamental rule to remember is that when passing hashes tosubroutines you can pass only one, and it must be the last argumentsupplied.

    This will not work.

    sub display

    {

    my (%hash, $regex) = @_;

    }

    2/22/201257

  • 8/3/2019 Introduction to Perl 2009

    58/109

    Confidential McAfee Internal Use Only

    Subroutines (contd..)

    Return Values

    The return value of any block, including those used insubroutines, is taken as the value of the last evaluatedexpression. For example:

    sub myfunc {

    $_[0]+$_[1];

    }The return value here is the result of the calculation.

    You can also explicitly return a value using the return keyword:

    sub myfunc {

    my $c=$_[0]+$_[1];return $c;

    }

    2/22/201258

  • 8/3/2019 Introduction to Perl 2009

    59/109

    Confidential McAfee Internal Use Only

    Subroutines (contd..) Return Context

    In order to discover the context in which a function has beencalled, you use the wantarray function.

    For E.g.

    sub hw {

    if (wantarray) {return('Hello','World',"\n");

    }

    else {

    return "HelloWorld\n";

    }

    }

    2/22/201259

  • 8/3/2019 Introduction to Perl 2009

    60/109

    Confidential McAfee Internal Use Only

    Subroutines (contd..)

    Prototypes

    A prototype definition is a parenthesized list of charactersmirroring the Perl variable type syntax (that is, $, @, %, and soon). It is placed after the sub keyword and subroutine name butbefore anything else, be it a subroutine definition, declaration, oranonymous subroutine:

    sub mysub (PROTOTYPE); # subroutine declaratio

    sub mysub (PROTOTYPE) {...} # subroutine definition

    $subref = sub (PROTOTYPE) {...} # anonymous subroutine

    For E.g.

    sub volume ($$$) {

    # ... as before ...

    }

    2/22/201260

  • 8/3/2019 Introduction to Perl 2009

    61/109

    Confidential McAfee Internal Use Only

    Subroutines (contd..)

    Prototypes can decide the parameter sequence.

    If the function has to receive a certain type of parameter as the firstone then in the prototype definition it must be prefixed with a \(backslash)

    E.g.

    sub Add(\@$$); indicates that the first argument must be an arrayor list followed by two scalars.

    2/22/201261

  • 8/3/2019 Introduction to Perl 2009

    62/109

    Confidential McAfee Internal Use Only

    Subroutines (contd..)

    Prototypes can decide the mandatory and optional parameters.

    Mandatory and optional parameters are separated by a ;(semicolon)

    E.g.sub CircleArea($;$)

    This indicates that the function takes in two parameters, out ofwhich one is mandatory

    2/22/201262

  • 8/3/2019 Introduction to Perl 2009

    63/109

    Perl Modules

  • 8/3/2019 Introduction to Perl 2009

    64/109

    Confidential McAfee Internal Use Only

    What are Perl Modules

    Perl modules are discrete components of any Perl program. A module is distinguished by a unique Namespace

    Modules can be written in two formats.

    Procedural Programming

    Object Oriented Programming

    2/22/201264

  • 8/3/2019 Introduction to Perl 2009

    65/109

    Confidential McAfee Internal Use Only

    Perl Module Structure

    package ;

    #Add the required modules to be used

    use strict;

    use warnings;

    #Define the subroutine required

    sub Loop ()

    {

    my $loopvalue=shift;

    return $loopvalue + 100;

    }

    #End the subroutine with this numerical

    1;

    2/22/201265

  • 8/3/2019 Introduction to Perl 2009

    66/109

    Confidential McAfee Internal Use Only

    Calling a Perl Module

    use Lib::MyMod;

    use strict;

    use warnings;

    MyMod::Loop(100);

    2/22/201266

  • 8/3/2019 Introduction to Perl 2009

    67/109

    Working with Files

  • 8/3/2019 Introduction to Perl 2009

    68/109

    Confidential McAfee Internal Use Only

    Working with Files

    Opening a File open FILEHANDLE, EXPR

    A filehandle is a named internal Perl structure thatassociates a physical file with a name.

    A filehandle can be reused.

    It is not permanently attached to a single file, nor is itpermanently related to a particular file name.

    The name of the filehandle and the name of the file are notrelated.

    As far as Perl is concerned, all operating systems support

    three basic filehandlesSTDIN, STDOUT, and STDERR

    2/22/201268

  • 8/3/2019 Introduction to Perl 2009

    69/109

    Confidential McAfee Internal Use Only

    Working with Files

    Open a File in Read only Mode:

    open (FH,< Data.txt);

    open (FH,Data.txt );

    Open a File inWrite Mode:

    open (FH,> Data.txt);

    This will Clear all the contents of a file before writing thenew contents.

    2/22/201269

  • 8/3/2019 Introduction to Perl 2009

    70/109

    Confidential McAfee Internal Use Only

    Working with Files

    Open a File for appending:

    open (FH,>> Data.txt );

    Open a File in both Read andWrite Mode:

    To open a file for both reading and writing prefix the > or < with a +sign.

    open(FH,+< Data.txt );

    2/22/201270

  • 8/3/2019 Introduction to Perl 2009

    71/109

    Confidential McAfee Internal Use Only

    Working with Files

    Reading Files

    Reading in Scalar context

    Open (FH,Data.txt);

    My $Line=;

    Print $Line;

    open(FH,Data.txt)

    While()

    {

    Print ;

    }

    2/22/201271

  • 8/3/2019 Introduction to Perl 2009

    72/109

    Confidential McAfee Internal Use Only

    Working with Files

    Reading Files in List Context.

    When in a list context all the line from the filehandle and stored inthe list.

    For e.g.Open(FH,Data.txt)

    My @Lines=;

    Print @Lines;

    2/22/201272

  • 8/3/2019 Introduction to Perl 2009

    73/109

    Confidential McAfee Internal Use Only

    Working with Files (contd..)

    Writing to a File

    Open(FH,> data.txt);

    Print FH This is a test\n;

    Closing a FileHandle

    Close(FH);

    2/22/201273

  • 8/3/2019 Introduction to Perl 2009

    74/109

    Confidential McAfee Internal Use Only

    Working with Files

    AutoFlush The amount of data that is read from a file or written to a file isdecided by the operating system. This is done for performancereasons and so that data is written in blocks. By default theautoflush is set to False.

    Open(FH,> Data.txt);

    Select(FH);

    $|=1;

    Print FH This is a test for autoflush enabled\n;

    Alternaively the module IO::Handle can be used for this,

    use IO::Handle;

    open(DOOR,"

  • 8/3/2019 Introduction to Perl 2009

    75/109

    Confidential McAfee Internal Use Only

    Working with Files (contd..)

    Handling Errors while opening files

    Using the keyword die

    Open(FH,Data.txt) or die $!;

    This will exit the program if the file cannot be opened. The systemerror message is stored in $!.

    The user can also defined his own custom message when theerror occurs.

    Open(FH,Data.txt) or die File Failed to open. Error $!;

    2/22/201275

  • 8/3/2019 Introduction to Perl 2009

    76/109

    Confidential McAfee Internal Use Only

    Working with Files (contd..)

    Handling Errors while opening files

    Using the Keyword warn

    The warn keyword will also throw an error but will not quit the

    program, the execution will continue from there on.

    Eg:

    Open(FH,Data.txt) or warn File open error $!\n;

    2/22/201276

  • 8/3/2019 Introduction to Perl 2009

    77/109

    Confidential McAfee Internal Use Only

    Working with Files (contd..)

    Reading the contents of a directory

    opendir(DIR,C:\\Program files);

    my @Contents=readdir(DIR);

    closedir(DIR);

    shift(@Contents); #Remove the . & .. symbols

    shift(@Contents);

    print @Contents;

    2/22/201277

  • 8/3/2019 Introduction to Perl 2009

    78/109

    Confidential McAfee Internal Use Only

    Working with Files (contd..) File Test Operators

    Operator Description

    -f Is it a File?

    -T Is it a text file?

    -X Is the file executable?

    -d Is the file a directory?

    -e Does the file exist?

    -s Returns the size of the file, withzero referring to an empty file.

    -z Is the file size zero?

    2/22/201278

  • 8/3/2019 Introduction to Perl 2009

    79/109

    Regular Expressions

  • 8/3/2019 Introduction to Perl 2009

    80/109

    Confidential McAfee Internal Use Only

    Regular Expressions

    The regular expression, also called regex or regexp, is a syntaxfor expressing search patterns for finding and extractingmatches within text. Regexps have a long history, and Perl simplementation.

    A key to writing good regular expressions is to understand the

    guiding principles of how the engine seeks a match. Perl sregular expression engine works on three basic principles, inthis order:

    Eagerness: It will try to match as soon as possible.

    Greediness: It will try to match as much as possible.

    Relentlessness: It will try every possible combination beforegiving up.

    2/22/201280

  • 8/3/2019 Introduction to Perl 2009

    81/109

    Confidential McAfee Internal Use Only

    Regular Expressions (contd..)

    Uses of Regular Expressions

    Pattern Matching (m//)

    Pattern Substitution (s///)

    Transliteration (tr///)

    2/22/201281

  • 8/3/2019 Introduction to Perl 2009

    82/109

    Confidential McAfee Internal Use Only

    Regular Expressions (contd..)

    Pattern Matching

    The match operator, m//, is used to match a string or statement to aregular expression.

    For example, to match the character sequence foo against the scalar$bar, you might

    use a statement like this:

    if ($bar =~ m/foo/)

    2/22/201282

  • 8/3/2019 Introduction to Perl 2009

    83/109

    Confidential McAfee Internal Use Only

    Regular Expressions (contd..)Modifier Description

    I Makes the match case insensitive

    m Specifies that if the string has newlineor carriage return characters, the ^

    and $ operators will now matchagainst a newline boundary, instead of

    a string boundary

    o Evaluates the expression only once

    s Allows use of . to match a newlinecharacter

    x Allows you to use white space in the

    expression for clarity

    g Globally finds all matches

    83 2/22/2012

  • 8/3/2019 Introduction to Perl 2009

    84/109

    Confidential McAfee Internal Use Only

    Regular Expressions (contd..)

    Quantifiers

    * Match 0 or more times + Match 1 or more time

    ? Match 0 or 1 time

    {n} Match exactly n times

    Character Class shortcuts \d [0-9] A digit

    \D [^0-9] A non digit

    \s [\s\t\r\f] A whitespace character

    \S [ \s\r\t\f] A non whitespace character

    \w [0-9a-zA-Z] A word character \W [^ 0-9a-zA-Z] A non word character

    2/22/201284

  • 8/3/2019 Introduction to Perl 2009

    85/109

    Confidential McAfee Internal Use Only

    Regular Expressions (contd..)

    Pattern Matching in Scalar Context

    $true = ($foo =~ m/foo/);

    Will set $true to 1 if$foo matches the regex, or 0 if the match fails.

    Pattern Matching in list Context

    my ($hours, $minutes, $seconds) = $time =~ m/(\d+):(\d+):(\d+)/;

    2/22/201285

  • 8/3/2019 Introduction to Perl 2009

    86/109

    Confidential McAfee Internal Use Only

    Regular Expressions (contd..)

    The $` $& and $ variables

    The $` variable has the string to left of the pattern match.

    The $& has the matched string.

    The $ has the string to the right of the pattern match.

    2/22/201286

  • 8/3/2019 Introduction to Perl 2009

    87/109

    Confidential McAfee Internal Use Only

    Regular Expressions (contd..)

    The Substitution Operator

    The substitution operator, s///, is really just an extension of the matchoperator that allows you to replace the text matched with some newtext. The basic form of the operator is

    s/PATTERN/REPLACEMENT/;

    For example, we can replace all occurrences of dog with cat using

    $string =~ s/dog/cat/;

    2/22/201287

  • 8/3/2019 Introduction to Perl 2009

    88/109

    Confidential McAfee Internal Use Only

    Regular Expressions (contd..)

    Note that the return value from any substitution operation is thenumber of substitutions that took place. In a typical substitution,this will return 1 on success, and if no replacements are made,then it will return 0a false response.

    The problem with modifying strings in this way is that weclobber the original value of the string in each casewhich is

    often not the effect we want. The usual alternative is to copy theinformation into a variable first, and then perform thesubstitution on the new variable:

    $newstring = $string;

    $newstring =~ s/cat/dog/;

    or on a single line

    ($newstring = $string) =~ s/cat/dog/;

    2/22/201288

  • 8/3/2019 Introduction to Perl 2009

    89/109

    Confidential McAfee Internal Use Only

    Regular Expressions (contd..)

    Transliteration or Translation (tr///)

    Transliteration is the process of replacing one letter withanother.

    Like the substitution operator they can be used with any suitabledelimiters, are bound to the input text with =~, have search and

    replace criteria, and even accept modifiers. The left-hand side of a transliteration is not a pattern but a list of

    characters to be transformed (that is, transliterated), and theright-hand side is the list of characters that they are transformedinto.

    Each character on the left-hand side is converted into thecorresponding character on the right, determined by theirrespective positions in the left and right lists.

    2/22/201289

  • 8/3/2019 Introduction to Perl 2009

    90/109

    Confidential McAfee Internal Use Only

    Regular Expressions (contd..)

    Transliteration converts the letter a into the letter z, the letter b into theletter y, and the letter c into the letter x:

    $text =~ tr/abc/zyx/;

    If the replacement list is longer than the search list, then the trailingcharacters are ignored. If shorter, Perl repeats the final character untilthe replacement list is long enough:

    $text =~ tr/abcd/zy/;

    The return value from a transliteration is a count of the number ofsuccessful translations.

    2/22/201290

    P l I B ilt F ti

  • 8/3/2019 Introduction to Perl 2009

    91/109

    Perl In Built Functions

  • 8/3/2019 Introduction to Perl 2009

    92/109

    Confidential McAfee Internal Use Only

    Perl In Built Functions

    1. abs

    abs EXPR

    Returns the absolute value ofEXPR or$_.

    2. binmode

    binmode FILEHANDLE.

    Sets the file read/write to binary mode.3. chdir

    chdir EXPR

    Changes the current working directory to EXPR. Returns 0 on failureand 1 on success.

    2/22/201292

  • 8/3/2019 Introduction to Perl 2009

    93/109

    Confidential McAfee Internal Use Only

    Perl In Built Functions4. chomp

    chomp EXPR

    chomp LIST

    chomp

    Removes the last character if it matches the value of$/ fromEXPR, each element ofLIST, or$_ if no value is specified.Returns Integer, number of bytes removed for all strings.

    5. chopchop EXPR

    chop LIST

    chop

    Removes the last character from EXPR, each element ofLIST,or$_ if no value is specified. Returns the the characterremoved from EXPR.

    2/22/201293

  • 8/3/2019 Introduction to Perl 2009

    94/109

    Confidential McAfee Internal Use Only

    Perl In Built Functions

    6. crypt

    crypt EXPR,SALT

    Encrypts the string EXPR using the system crypt( ) function. The

    value ofSALT is used to select an encrypted version from one of anumber of variations. Note that there is no equivalent decryptionfunction. You cannot (easily) decrypt a string that has beenencrypted in this way. Its normally used one way, first to encrypt astring, and then to encrypt a password to compare against theencrypted string. If youre using it in this

    form, then consider supplying the encrypted password as theSALT.

    2/22/201294

  • 8/3/2019 Introduction to Perl 2009

    95/109

    Confidential McAfee Internal Use Only

    Perl In Built Functions

    7. defined

    defined EXPRdefined

    Returns true if EXPR has a value other than the undef value, orchecks the value of $_ if EXPR is not specified. This can be

    used with many functions to detect a failure in operation, sincethey return undef if there was a problem. A simple Boolean testdoes not differentiate between false, zero, an empty string, orthe string 0, which are all equally false. If EXPR is a function orfunction reference, then it returns true if the function has beendefined.When used with entire arrays and hashes, it will notalways produce intuitive results. If a hash element is specified, it

    returns true if the corresponding value has been defined, butdoes not determine whether the specified key exists in the hash

    2/22/201295

  • 8/3/2019 Introduction to Perl 2009

    96/109

    Confidential McAfee Internal Use Only

    Perl In Built Functions

    8. eof eof FILEHANDLEeof()

    eof

    Returns true if the next read on the specified FILEHANDLE will

    return an end-of-file condition, or ifFILEHANDLE is not currently

    associated with an open file. IfFILEHANDLE is not specified, it

    returns the condition for the last accessed file. In Scalar Context:

    undefifFILEHANDLE is not at end of file 1 ifFILEHANDLE will

    report end of file on next read.

    2/22/201296

  • 8/3/2019 Introduction to Perl 2009

    97/109

    Confidential McAfee Internal Use Only

    Perl In Built Functions

    9. eval

    eval EXPR

    Evaluates EXPR at execution time as ifEXPR were a separate Perlscript. This allows you to use a separate, perhaps user-supplied,piece of Perl script within your program. An eval EXPR statement isevaluated separately each time the function is called. . Anyexceptions raised by the interpreter, die, orwarn are contained in$@.

    2/22/201297

  • 8/3/2019 Introduction to Perl 2009

    98/109

    Confidential McAfee Internal Use Only

    Perl In Built Functions

    10. exec

    exec EXPR LISTExecutes a system command (directly, not within a shell) and neverreturns to the calling script.

    11. exit

    exit EXPREvaluates EXPR, exits the Perl interpreter, and returns the value asthe exit value.Always runs all END{} blocks defined in the script(and imported packages) before exiting. IfEXPR is omitted, thenthe interpreter exits with a value of 0. Should not be used to exitfrom a subroutine; use die or use return.

    2/22/201298

    P l I B ilt F ti

  • 8/3/2019 Introduction to Perl 2009

    99/109

    Confidential McAfee Internal Use Only

    Perl In Built Functions

    12. gmtimegmtime EXPRgmtimeReturns a list of values corresponding to the date and time asspecified by EXPR, or date and time returned by the time function ifEXPR is omitted, localized for the standard Greenwich mean time.The values returned are as follows:

    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =gmtime(time);

    The array elements are numeric, taken from the system struct tm.The value of $mon has a range of 0..11, $wday has a range of 0..6(SundaySaturday), and $year is returned as the number of yearsfrom 1900.

    2/22/201299

    P l I B ilt F ti

  • 8/3/2019 Introduction to Perl 2009

    100/109

    Confidential McAfee Internal Use Only

    Perl In Built Functions

    13. hex

    hex EXPR

    hex

    Interprets EXPR as a hexadecimal string and returns the value,or converts $_ ifEXPR is omitted.

    14. intint EXPR

    int

    Returns the integer element ofEXPR, or$_ if omitted. The intfunction does not do rounding. If you need to round a value up toan integer, you should use sprintf

    2/22/2012100

    P l I B ilt F ti

  • 8/3/2019 Introduction to Perl 2009

    101/109

    Confidential McAfee Internal Use Only

    Perl In Built Functions

    15. index

    index STR, SUBSTR, POSITION

    index STR, SUBSTR

    Returns the position of the first occurrence ofSUBSTR in STR,starting at the beginning (starting at zero), or from POSITION ifspecified.

    Returns in Scalar Context

    -1 on failure

    Position of matching string (starting at zero for the first character).

    Also see rindex

    2/22/2012101

    P l I B ilt F ti

  • 8/3/2019 Introduction to Perl 2009

    102/109

    Confidential McAfee Internal Use Only

    Perl In Built Functions

    16. length

    length EXPR

    length

    Returns the length, in characters, of the value ofEXPR, or$_ if not specified. Use scalar context on an array or hashif you want to determine the corresponding size.

    2/22/2012102

    P l I B ilt F ti

  • 8/3/2019 Introduction to Perl 2009

    103/109

    Confidential McAfee Internal Use Only

    Perl In Built Functions

    17. mkdir

    mkdir EXPR,MODEMakes a directory with the name and path EXPR using themode specified by MODE,which should be supplied as an octalvalue for clarity.

    Return in Scalar Context

    0 on failure

    1 on success18. ord

    ord EXPR

    ord

    Returns the ASCII numeric value of the character specified by

    EXPR, or$_ if omitted

    2/22/2012103

    P l I B ilt F ti

  • 8/3/2019 Introduction to Perl 2009

    104/109

    Confidential McAfee Internal Use Only

    Perl In Built Functions

    19. rand

    rand EXPR

    rand

    Returns a random fractional number between 0 and the positivenumberEXPR, or 1 if not specified. Automatically calls srand toseed the random number generator unless it has already beencalled.

    Returns in Scalar Context

    Floating point number.

    2/22/2012104

    Perl In Built Functions

  • 8/3/2019 Introduction to Perl 2009

    105/109

    Confidential McAfee Internal Use Only

    Perl In Built Functions

    20. rmdir

    rmdir EXPR

    rmdir

    Deletes the directory specified by EXPR, or$_ if omitted. Onlydeletes the directory if the directory is empty.

    2/22/2012105

    Perl In Built Functions

  • 8/3/2019 Introduction to Perl 2009

    106/109

    Confidential McAfee Internal Use Only

    Perl In Built Functions

    21. split

    split /PATTERN/, EXPR, LIMIT

    split /PATTERN/, EXPR

    split /PATTERN/

    split

    Splits a string into an array of strings, returning the resultant list. Bydefault, empty leading fields are preserved and empty trailing fieldsare deleted.

    2/22/2012106

    Perl In Built Functions

  • 8/3/2019 Introduction to Perl 2009

    107/109

    Confidential McAfee Internal Use Only

    Perl In Built Functions

    22. system

    system PROGRAM, LIST

    system PROGRAM

    Executes the command specified by PROGRAM, passing LIST asarguments to the command. The script waits for execution of thechild command to complete before continuing. IfPROGRAM is theonly argument specified, then Perl checks for any shellmetacharacters and, if found, passes PROGRAM unchanged to theusers default command shell.

    2/22/2012107

    Perl In Built Functions

  • 8/3/2019 Introduction to Perl 2009

    108/109

    Confidential McAfee Internal Use Only

    Perl In Built Functions

    23. time

    time

    Returns the number of seconds since the epoch (00:00:00 UTC,January 1, 1970, for most systems; 00:00:00, January 1, 1904, forMac OS). Suitable for feeding to gmtime and localtime.

    2/22/2012108

    Thank You!!

  • 8/3/2019 Introduction to Perl 2009

    109/109

    Thank You!!