Perl

23
PERL PERL Practical Extraction & Reporting Language Practical Extraction & Reporting Language

description

This presentation is about PERL basics for beginners.

Transcript of Perl

Page 1: Perl

PERLPERLPractical Extraction & Reporting LanguagePractical Extraction & Reporting Language

Page 2: Perl

HistoryDeveloped by Larry Wall in 1987.A combination of C and Unix Shell programming language.Originally developed for UNIX, but now runs under all OS.

“A good perl program is one that gets the job done before your boss fires you.”

Larry Wall, the creator of Perl.

Page 3: Perl

Contents

IntroductionVariablesOperatorsConditional Statements and LoopsRegular ExpressionsSubroutinesFile HandlingMany more....

Page 4: Perl

File Management Contd..binmode(HANDLE): change file mode from text to binary unlink("myfile"): delete file myfile rename("file1","file2"): change name of file file1 to file2 mkdir("mydir"): create directory mydir rmdir("mydir"): delete directory mydir chdir("mydir"): change the current directory to mydir system("command"): execute command command die("message"): exit program with message message warn("message"): warn user about problem message

Page 5: Perl

Introduction

Interpreted language, optimized for string manipulation, I/O and system tasks. Speed of development Easy to use, portable Freely available Extension is .pl Execution : perl file.pl All perl program goes through 2 phases :

a compile phase where the syntax is checked and the source code, including any modules used, is converted into bytecode.

a run-time phase where the bytecode is processed into machine instructions and executed.

Page 6: Perl

Basic Syntax

All statements should end with ';'

# is used for commenting a line

Perl is case sensitive

Basic options : -c, -v, -w

Page 7: Perl

Variables

Three basic data types, scalars, arrays and hashesScalars : Holds a single value of any type.

$var1 = 123$var2 = “Hello, how r u”$var3 = 1.23$1var = 123 # Error

Page 8: Perl

Built-in Functions

Chomp() : The chomp() function will remove (usually) any newline character from the end of a string.Chop() : The chop() function will remove the last character of a string (or group of strings) regardless of what that character is.

Page 9: Perl

Control FlowSyntax same as C

If Construct :

if (expr) {stmt block;}

If Else Construct :

if (expr) {stmt block 1;}else {stmt block 2;}

If Else If Construct :

if (expr1) {stmt block 1;}elsif (expr2) {stmt block 2;}else{default stmt;}

Page 10: Perl

LoopsLoops in Perl are written in the same way as in C.Only remember that the loop variable is a scalar variable and must be preceded by a $ sign.

while (expr) { stmt block;}

do { stmt block;} while (expr);

for (expr1 ; expr2 ; expr3) { stmt block;}

foreach var (listexpr) { stmt block;}

Page 11: Perl

ForeachBehaves same as for loop.

foreach $person (@names) {print "$person";}

$_ : Default Input and Pattern Searching Variable

foreach (@names) {print "$_";}

Page 12: Perl

ListsList is a group of scalars used to initialize and array or hash.Elements can be any type of scalar data.List functions :

Join : Joins list values

Split : A string is splited

Map : Evaluates expression or blocks

Grep : Returns a sublist of list for each a specific criteria is true

Page 13: Perl

ArraysIn Perl an array does not have to be declared before it is used. The size of an array increases dynamically. An array variable has an @ before it.

@num = (1,2,3,4,5);@num = (1..5);@mix_arr = ("Tom", 5, "Cruise", 90, "Jane", 35.67 34, 78, "I am

Bond");

You can assign an array element to any index - even one that is beyond the current range of index numbers. The in-between elements are assigned null values.

Page 14: Perl

Push, Pop and SpliceThe push function pushes an element onto an array. If the last

element in an array has index 5, pushing an element onto the array makes it the element with index 6.

The syntax is:push(@arrayname, value);

The pop function pops off the last element off the array. So, if the last element in the array @myarray is 99, then the statement

$num = pop(@myarray);

assigns the value 99 to $num.

The splice function is used to pop more than one element.

(splice(@myarray, -3) will remove three elements from the end of the array

Page 15: Perl

Unshift and ShiftThese work like the push and pop operators, but add and

subtract from the beginning of an array rather than the end.

The syntax isunshift(@arrayname, value);

shift(@arrayname);

Page 16: Perl

Associative Array or HashHashes are a list of scalars, but instead of being accessed by

index number, they are accessed by a key.Syntax : %myhash = ('Key1', 'Val1', 'Key2', 'Val2', 'Key3', 'Val3')

Index No Value

0 Spain

1 Belgium

2 Germany

3 Netherlands

Key Value

SP Spain

BL Belgium

GE Germany

NL Netherlands

Page 17: Perl

Perl Command LineRead from command prompt.

Go to example.

Page 18: Perl

Hash FunctionsAssigning : $countries{PT} = 'Portugal';Deleting : delete $countries{NL};Print all the keys : print keys %countries;Print all the values : print values %countries;A slice of hash : print @countries{'NL', 'BL'};How many elements : print scalar(keys %countries);Does the key exist : print “I exist \n” if exists $countries{'NL'};

Page 19: Perl

SubroutineSyntax for subroutines :

Sub subname { Stmt block;}

Value of the last expression evaluated by the subroutine is automatically considered to be subroutine's return value.

Foreach $var (&subname) { Stmt block;}

Perl defines 3 special subroutines that are executed at specific times.

BEGIN : Called when our program starts running.END : Called when the program terminates.AUTOLOAD : Called when the program cannot find a subroutine it is

supposed to execute.

Page 20: Perl

File Managementopen(INFILE,"myfile"): reading open(OUTFILE,">myfile"): writing open(OUTFILE,">>myfile"): appending open(INFILE,"someprogram |"): reading from program open(OUTFILE,"| someprogram"): writing to program opendir(DIR,"mydirectory"): open directo

Operations on an open file handle$a = <INFILE>: read a line from INFILE into $a @a = <INFILE>: read all lines from INFILE into @a $a = readdir(DIR): read a filename from DIR into $a @a = readdir(DIR): read all filenames from DIR into @a read(INFILE,$a,$length): read $length characters from INFILE

into $a print OUTFILE "text": write some text in OUTFILE

Close files / directoriesclose(FILE): close a file closedir(DIR): close a directory

Page 21: Perl

Perl DebuggerPerl -d myprogram.pl

Debugger commands :

l : lists the next few statements.l 10 : specifies the line numberl 10-15 : display a range of linesl subroutine : display subroutine- : display the immediately preceding the last displayed line/search'/ : Search for a line containing the pattern?backsearch? : To search backword for a patternS : lists all the subroutines in the files : execute single statement and displays next statement to executen : same as s command, but n command does not enter subroutine, directly execute

itr : if we are inside a subroutine and do not want to execute further, this command

finishes subroutine execution and returns to the last statement called the subroutine

X : print the value of a particular variableb 10 : set a breakpoint to our programc : after breakpoint set, this command execute till the breakpointL : display all the breakpointsB 10 : delete break pointsB * : delete all breakpoints

Page 22: Perl

ResourcesPerl.comPerl.orgLists.perl.orgPerlmonksStackoverflowPerl mongersSearch.cpan.org

Page 23: Perl

Continued...