perl  programming language 

33
8/14/2019 PERL Programming Language http://slidepdf.com/reader/full/perlprogramminglanguage 1/33 PERL - Programming Language 25th ofN ov, 2006 H yderabad, India

Upload: fedyaya

Post on 30-May-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 1/33

PERL - Programming Language

25th of N ov, 2006

H yderabad, India

Page 2:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 2/33

 We appreciate

Page 3:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 3/33

Outline● Perl What & why ?

● Perl Culture.

● #!/usr/bin/perl

● Data Structure (Arrays & hashes)● Regular expression.

● Subroutines

Modules● Basic Object-Oriented Programming 

● Error Handling 

Page 4:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 4/33

Outline●Summary / Take home

●Resources & references.

●Books

●Special thanks● About us

Page 5:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 5/33

Perl What & why ?

  Perl = Practical Extraction and Report Language

Developed by Larry Wall (late 80's) as a replacement for awk.

Since then perl has mushroomed into a powerful & popular language withlots of module contributed by open source community.

An extremely useful tool to know because it:

* runs on Unix, Linux, Mac, Amiga, OS/2, VMS, DOS, Windows, ...

* is a de facto standard for complex scripting tasks (once were shell scripts)

* has standard libraries for many applications (Web/CGI, database, ...)

Page 6:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 6/33

Perl Culture

In Many ways perl is a language for hackers not for computer scientist.

Perl is designed by people who prefer language like c, which aew more rigid and closer to machine code.

Larry wall's perspective is ----"Perl is a language for getting your job done."

Popular slogans in perl:"Easy things should be easy, and hard things should be possible"

TMTOWTDI "There's More Then One Way To Do It"

Page 7:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 7/33

#!/usr/bin/perl

 We generally start a Perl program with a line, which looks like one of these:

#!/usr/bin/perl#!/usr/local/bin/perl4#!/usr/local/bin/perl5

#!/usr/local/bin/perl -w ........etc

 Why we need this ?

It is not necessary on many systems, but when it is, it isSo its a good habit to start Program with this line.

The basic motive of this line is to tell the server which version of perlto use,by pointing in the server directory of the Perl executable.

Page 8:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 8/33

Page 9:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 9/33

Page 10:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 10/33

Regular Expressions cont...

Perl extends POSIX regular expressions with some shorthand:

\d matches any digit, i.e. [0-9]\D matches any non-digit, i.e. [^0-9]\w matches any "word" char, i.e. [a-zA-Z_0-9]

\W matches any non "word" char, i.e. [^a-zA-Z_0-9]\s matches any whitespace, i.e. [ \t\n\r\f]\S matches any non-whitespace, i.e. [^ \t\n\r\f]

Perl also adds some new anchors to regexps:

\b matches at a word boundary 

\B matches except at a word boundary 

Page 11:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 11/33

Regular Expressions cont...

 And generalizes the repetition operators:

patt* matches 0 or more occurrences of pattpatt+ matches 1 or more occurrences of pattpatt? matches 0 or 1 occurrence of pattpatt{n,m} matches between n and m occurrences of patt

Examples:E.g. /ab+/ matches abbbabbbb not abbbabbbbE.g. /ab+?/ would match abbbabbbbExample:

$pattern = "ab+";$replace = "Yod";

$text = "abba";

$text =~ s/$pattern/$replace/;

# converts "abba" to "Yoda"

Page 12:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 12/33

Regular Expressions cont...

Examples:

$marks = "99,67,85,48,77,84";

@listOfMarks = split(/,/, $marks);

# assigns (99,67,85,48,77,84) to @listOfMarks

$sum = 0;foreach $m (@listOfMarks) {

$sum += $m;}

$newMarks = join(':',@listOfMarks);# assigns "99:67:85:48:77:84" to $newMarks

Page 13:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 13/33

Page 14:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 14/33

Pragmas & Modules

.Perl provides a way of controlling some aspects of the interpreter's behaviour(through pragmas) and is an extensible language through the use of compiled modules,of which there is a large number. Both are introduced by the use keyword.

Pragmas* use English; allow names for built-in vars, e.g., $NF = $. and $ARG = $_.

* use integer; truncate all arithmetic operations to integer, effective to theend of the enclosing block.

* use strict 'vars'; insist on all variables declared using my.

Modules:

.A Perl Module is a self-contained piece of [Perl] code that can be used by a Perlprogram (or by other Perl modules)

.It is conceptually similar to:.a C link library .a C++/Java class

Page 15:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 15/33

 Writing Module

Before making a PM.Chose an appropriate name for the PM

.Each Perl Module has an unique name. Perl provides a hierarchal name spacefor modules, similar to the name space for Java classes.

. Components of a module name are separated by double colons i.e. IEPM::PingERLets start to make PMCreate the Perl Module Tree:

$ h2xs -AX -n IEPM::PingER

-A omits the Autoloader code (best used by modules that

define a large number of infrequently used subroutines)

-X omits XS elements (eXternal Subroutine, whereeXternal means external to Perl, i.e. C)

-n specifies the name of the module

Page 16:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 16/33

Page 17:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 17/33

Tips for writing code of a PM

.A PM can use other Pms

.use strict; (i.e. $IEPM::PingER::var)

.use 5.6.1;

.$VERSION=1.03;

.@EXPORT = qw(ping_it);

.sub ping_it { }

.1;

.__END__

How to use a PM in a Perl Programuse IEPM::PingER;$answer = ping_it (host.domain.edu);

Page 18:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 18/33

Example :.package IEPM::PingERuse 5.008;use strict;use warnings;use Carp;require Exporter;our @ISA = qw(Exporter);

use Time::CTime;use DB_Files;our @EXPORT = qw(log_it ping_it);our $VERSION = '1.03';

PingER.PMsub ping_it {

my ($ping_cmd,$dest_name,$dest_ip,$ping_interval, $ping_size, $ping_count) = @_;............return ($time, $packets_sent, $packets_rcvd,$min, $avg, $max, \@seqno, \@pingtimes);

}

Page 19:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 19/33

Example: cont...timeping.pl

use IEPM::PingER;

($time, $packets_sent, $packets_rcvd, $min,$avg, $max, $seqno, $pingtimes) =

ping_it($ping_cmd,$dest_name,$dest_ip,

$ping_interval, 1000, $ping_count);

Preparing the Package for shipping 

Prepare the package for shipping is straightforward:

$ perl Makefile.PL; make; make dist;

The commands above create the compressed archive:IEPM-PingER-1.03.tar.gz

Page 20:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 20/33

Basic Object-Oriented Programming 

An object (also called an instance), like a given car, has the following:* Attributes or properties (color: red; seating capacity: 4; power: 180 HP)* Identity (my car is different from your car)* Behavior (it can be steered and moved forward and backward)

.Objects of a certain type are said to belong to a class.

.My car and your car belong to the class called Car or, if you are not too worried

about specific details, to a class called Vehicle.

 Abstraction-- Information about an object (its properties) can be accessed in a manner that

isolates how data is stored from how it is accessed and used.Encapsulation

-- The information about an object and functions that manipulate theinformation (its methods) are stored together.

Inheritance-- Classes can inherit properties and methods from one or more parent classes.

Polymorphisms-- A child class can redefine a method already defined in the parent class.

Page 21:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 21/33

Page 22:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 22/33

Page 23:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 23/33

Error handling in perl

.Patterns in perlHandling errors is the BANE of any program. In some programming languages,error handling is tedious to do properly, so we often forget to do it,or we do it improperly. In Perl, there are a few common idioms forhandling errors that are both robust and easy to use.

FILE *fp; open(my $fh "/my/file");

fp = fopen("/my/file", "r"); if (!$fh) {if (fp == NULL) { return -1; # ERROR - could not open filereturn -1; // ERROR - could not open file }}

Here is a more natural expression of the same basic intent in Perl:open(my $fh "/my/file") or return -1;

In many simple scripts, it is common or even advisable to terminate immediately at the first point of failure. This pattern is known as “open or die,” and it isone of the most common patterns in Perl programming:open(my $fh "/my/file") or die "Cannot open '/my/file'\n";

Page 24:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 24/33

Error handling cont...

Handling error..The "open or die" , is one of the most common patterns in perl programming.

.The key is ultra law precedence 'or' operator that connects two statements

.This pattern uses 'or' operator instead of '||'(boolean or) which is higherprecedence for couple of the reasons

.It is clearer when reading the code.

.or is ultra law precedence operator so there is no ambiguity.

open FH, "/my/file" or die "Cannot open '/my/file'\n";open FH, "/my/file" || die “Cannot open '/my/file'\n";

. This die clause will execute only when there is open failure.. This includes functions like chdir,mkdir,unlink & so on.

. For conciseness, perl programmer generally call this overall patternas "open or die".

Page 25:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 25/33

Error handling cont...

Recovering from errors.open or die pattern terminates your script at the first sign of error..sometimes you do not want to terminate your script you want to exit immediately form subroutine/loop or display warning.

.Even though this pattern is called "open or die".

.Any recovery action fits into this , including return,warn or even print.

sub get_lines {my $filename = shift;my @lines;open(my $in, $filename) or return;

 while (<$in>) {next if m/^$/; ## Skip blank linesnext if m/^#/; ## Skip comment linespush (@lines, $_);}return @lines;}

Page 26:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 26/33

Page 27:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 27/33

Error handling cont...Example.

1: package Testing;2: use Carp;3:4: sub test_carp {5: carp "Testing carp";6: }7:8: sub test_warn {9: warn "Testing warn";10: }11:12: package main;13:

14: Testing::test_carp();15: Testing::test_warn(); And here is the result:Testing carp at test.pl line 14Testing warn at test.pl line 9

Page 28:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 28/33

Error handling cont...

.Returning false is often sufficient for signaling an error.

.But sometimes returned values are false but they do not signal any error.

.In such situation its not feasible to say that "Any false value" signals an error.

.In such situation it is generally better to say the undefined value signals an error.

Example: #Looping line by line is to process one line at a time  while (<>) { #it can happen that it reads an empty string from a file ,... #or a line containing single char 0.} #these values should not signal end of loop.

  while (defined($_ = <>)) #it will read every line form file.{ #including blank line & lines that contains zero.... #The undefined value will be returned when there

#is an error reading a file such as <EOF>} #defined(add_user()) or die 'can not add user'.

Page 29:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 29/33

Summary / Take home●

The language is intended to be practical (easy to use,efficient, complete) rather than beautiful (tiny, elegant,minimal)

● Perl is powered by regular expressions. Get used to using 

regexps and their operators. Quickly.●Catch errors before you get far away,as a horrible form of 

 Action At a Distance.

● Perl code can be debug by running script with -d option.

Page 30:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 30/33

Resources●

 Active perl online documentation.http://aspn.activestate.com/ASPN/docs/ActivePerl/5.8/lib/ActivePerl.ht

● Comprehensive Perl Archive Network (CPAN)http://cpan.org/

Perl/CGI Scripting http://www.cse.unsw.edu.au/~cs2041/lec/05cgi/

●  Advance perl programming http://www.unix.org.ua/orelly/perl/advprog/index.htm

Perl Wikipediahttp://en.wikipedia.org/wiki/Perl

Page 31:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 31/33

Books

Page 32:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 32/33

CommVault Systems (India) Pvt. Ltd.

http://www.commvault.com/

CommVault is a Storage Management, Backupand Disaster Recovery company incorporated in USA  with its Global Development Centre in Hyderabad, AP.

Special thanks

Page 33:  PERL  Programming Language 

8/14/2019  PERL   Programming Language 

http://slidepdf.com/reader/full/perlprogramminglanguage 33/33

 About us ...

irc

#twincling 

helpline+91-99494 96414

more [email protected] 

 website

 www.twincling.org 

mailing list

groups.yahoo.com/group/twincling 

forum (softw are --> tw incling)

http://www.nabble.com/twincling-f15741.html

CharterPromote, Develop and Showcase Open Source software.