Scripting Through PERL

Embed Size (px)

Citation preview

  • 7/30/2019 Scripting Through PERL

    1/22

    -- Satish Kumar Grandhi

    Scripting through PERL

  • 7/30/2019 Scripting Through PERL

    2/22

    Contents

    Introduction & Running Perl

    Printing

    Scalar Variables

    Operations and Assignment

    Arrays & Associative Arrays Loops

    Conditionals

    File handling

    Regular Expressions

  • 7/30/2019 Scripting Through PERL

    3/22

    What is PERL ?? Practical Extraction and Report Language, designed by Larry

    Wall

    Has the power and flexibility of a high-level programminglanguage such as C.

    Like shell script languages, Perl does not require a specialcompiler and linker to turn the programs you write into workingcode.

    Ideal for producing quick solutions to small programmingproblems, or for creating prototypes to test potential solutions tolarger problems.

  • 7/30/2019 Scripting Through PERL

    4/22

    Interpretive Versus Compiled

    Languages

    Compiled language translates the user code into machine-readablecode by a special program known as a compiler.

    In addition, library code might need to be added by another specialprogram known as a linker.

    After the compiler and linker have done their jobs, the result is a

    program that can be executed on your machine-assuming, of course,that you have written the program correctly. If not, you have tocompile and link the program all over again.

    Interpretive languages takes very little time to run a program.However, cannot run unless the interpreter is available.

    Compiled programs, on the other hand, can be transferred to any

    machine that understands them.

  • 7/30/2019 Scripting Through PERL

    5/22

    Simple ProgramUse .pl extensionPerl programName (to run the program)

    Perl -d programName (to run using debugger)

    Perl wprogramName (to run with warnings)

    # character -- Perl comment character

    /usr/local/bin/perl -- Perl executable location

    $inputline = ; reads the data from

    keyboard

    #!/usr/local/bin/perl

    $inputline = ;

    print( $inputline );

    Output :

    Hello world

    Hello world

  • 7/30/2019 Scripting Through PERL

    6/22

    Perl Scalar Variables Scalar data can be number or string

    Floating-point values

    $x = 3.14;

    $y = -2.78;

    Integer values

    $a = 1000;

    $b = -2000;

    String values

    $str = "this is a string in Perl".

  • 7/30/2019 Scripting Through PERL

    7/22

    Operations on scalar variables$a = 1 + 2; # Add 1 and 2 and store in $a$a = 5 % 2; # Remainder of 5 divided by 2

    $b = ++$a; # Increment $a and then return it

    $b = $a++; # Return $a and then increment it

    $b = --$a; # Decrement $a and then return it

    $b = $a--; # Return $a and then decrement it

    Concatenation

    $a = Monday; $b=Tuesday;

    $c=$a. .$b;$c= Monday Tuesday;

    $d= $a. .and. .$b;

    $d=Monday and Tuesday;

  • 7/30/2019 Scripting Through PERL

    8/22

    Perl conditional statements - IFif(condition){

    if-statements;

    }

    else{

    else-statements;

    }EXAMPLE

    $x = 5;

    $y = 10;

    if($x == $y){

    print "x is equal to y";}else{

    print "x is not equal to y";}

  • 7/30/2019 Scripting Through PERL

    9/22

    Perl Loops For, Whilewhile ($count

  • 7/30/2019 Scripting Through PERL

    10/22

    Arrays Initialize an array/set to null

    @colours=();

    Functionspush andpop

    #assign elements to array @colours

    @colours=(red,blue,yellow);

    #use push function to add an element to the end of array

    push(@colours,green);

    #colours now contains: red,blue,yellow,green

    #use pop function to remove an element from the end of array

    pop(@colours);

    #colours now contains red, blue, yellow

  • 7/30/2019 Scripting Through PERL

    11/22

    Continued#Functions shiftand unshift

    @colours=(red,blue,yellow);

    $new_el=green;

    #use unshift to append $new_el to start of array

    unshift(@colours, $new_el);

    @colours is now: green,red,blue,yellow

    #use shift to remove an element from the front of array

    shift(@colours);

    @colours is now: red,blue,yellow

  • 7/30/2019 Scripting Through PERL

    12/22

    Working with arrays

    @colours = (red,blue,yellow);

    print $colours*0+ #prints: red

    $#colours #index of last element of array

    print $colours*$#colours+; #prints: yellow

    print @colours #prints: redblueyellow

    print @colours #print: red blue yellow

    $colours = "@colours"; #assigns colours to string

    print $colours; #prints: red blue yellow

  • 7/30/2019 Scripting Through PERL

    13/22

    Associative arrays / hashes

    The elements of associative arrays have keys with associated values

    Initialize

    %Mygrades=();

    Assign elements

    $Mygradesenglish-=80;

    $Mygradesirish-=70;

    $Mygradesmaths-=50;

    Printing

    while(($key,$value)=each(%Mygrades))

    print $key => $value\n;-

    Prints: english => 80

    irish => 70

    maths => 50

  • 7/30/2019 Scripting Through PERL

    14/22

    File handling

    Opening a file

    $filename =MyFile.txt;

    open(FILE,MyFile.txt") || die ("Cannot open file MyFile : $!\n");

    File: Filehandle for MyFile.txt

    Die: If the file cannot be opened for reading the program will die(ie quit

    execution) and the reason for this will be returned in $!

    The above file has been opened for reading : open(FILE,..);

    To open a file for writing:open(FILE,>OutFile.txt);

    Outfile.txt will be overwritten each time the program is executed

    To open a file for appending:

    open(FILE,>>..Append.txt);

    Close File: close(FILE);

  • 7/30/2019 Scripting Through PERL

    15/22

    File processing

    #open input file for reading

    open(IN,InFile.txt)|| die Cant open file.$!\n;

    #open output file for writing

    open(OUT,>OutFile.txt)|| die Cant open file.$!\n;

    while() #while there are still lines in InFile.txt

    { $line=$_; #read in the lines one at a time

    chop($line); #remove end of line character

    if($line eq Number 7){ print OUT $line\n; - #endif

    }#endWhile

    close(IN); close(OUT); #close Files

  • 7/30/2019 Scripting Through PERL

    16/22

    Regular expressions

    #A regular expression is contained in slashes, and matching occurs withthe =~ operator.

    #The following expression is true if the string the appears in variable

    $sentence.

    $sentence =~ /the/#The RE is case sensitive, so if $sentence = "The quick brown fox"; then

    the above match will be false.

    $sentence !~/the/ (True) because the (lower case) is not in $sentence

    #To eliminate case use i

    $sentence =!/the/i; (True) because case has been eliminated with i

  • 7/30/2019 Scripting Through PERL

    17/22

    Special characters used to match

    . # Any single character except a newline

    ^ # The beginning of the line or string

    $ # The end of the line or string

    * # Zero or more of the last character

    + # One or more of the last character

    ? # Zero or one of the last character

    \s+(matches one or more spaces)

    \d+ (matches one or more digits)\t (matches a tab)

    \n (matches a new line)

    \b (matches a word boundary)

  • 7/30/2019 Scripting Through PERL

    18/22

    An Example using REs

    TASK : We have a file containing lines in different formats. We want topick out the lines which start with a digit and end in a full stop.

    while()

    {

    $line=$_;

    chop($line);

    if($line =~/^\d+(.*)\.$){print $line\n;}

    }

    ^\d+ (specifies that $line must begin with a digit)

    (.*) This digit can be followed by any character any

    no. of times

    \. This is followed by a full stop (The slash is

    included to de specialise the . )

    $. This specifies that the previous character (.)must be the last on the line

  • 7/30/2019 Scripting Through PERL

    19/22

    REs contd

    [a-z] (matches any lower case letter)

    [a-zA-z] (matches any letter)

    In the previous example a line was matched under the followingcondition:

    if($line =~/^\d+(.*)\.$)

    The RE would match the line: 10 people went to the concert.

    \d+ = 10; (.*) = people went to the concert;

    Perl groups the elements specified by (.*) together and assigns it adefault variable name : $1;

    Print $1\n; # prints : people went to the concert

  • 7/30/2019 Scripting Through PERL

    20/22

    Substitution

    #substitution is a useful facility in perl which can be used to replace oneelement with another

    #replaces all instances of london (lc) in $sentence to London (uc);

    $sentence =~ s/london/London/;

    #replaces all instances of red in $sentence to blue

    $sentence =~s/red/blue/;

    Example

    $sentence= the red and white dress;

    $sentence =~s/red/blue;

    $sentence is now = the blue and white dress

  • 7/30/2019 Scripting Through PERL

    21/22

    Split

    #split is a useful function : splits up a string and puts it on an #array

    $example = My name is Nano Gough;

    @name=split(/\s+/,$example);

    @name = My, name, is, Nano, Gough

    #using split you can also assign elements to variables

    $name = Nano:Gough;

    ($first_name, $surname)=split(/\:/,$name);

    $first_name = Nano;

    $surname=Gough;

  • 7/30/2019 Scripting Through PERL

    22/22

    References

    http://www.perltutorial.org/http://www.pageresource.com/cgirec/index2.htm