PERLPERL
Practical Extraction & Reporting LanguagePractical Extraction & Reporting Language
History
Developed 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.
Contents
Introduction
Variables
Operators
Conditional Statements and Loops
Regular Expressions
Subroutines
File Handling
Many more....
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
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.
Basic Syntax
All statements should end with ';'
# is used for commenting a line
Perl is case sensitive
Basic options : -c, -v, -w
Variables
Three basic data types, scalars, arrays and hashes
Scalars : Holds a single value of any type.
$var1 = 123
$var2 = “Hello, how r u”
$var3 = 1.23
$1var = 123 # Error
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.
Control Flow
Syntax same as C
If Construct :
if (expr) {
stmt block;
}
If Else Construct :
Loops
Loops 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) {
Foreach
Behaves same as for loop.
foreach $person (@names) {
print "$person";
}
$_ : Default Input and Pattern Searching Variable
foreach (@names) {
print "$_";
}
Lists
List 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
Arrays
In 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.
Push, Pop and Splice
The 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)
Unshift and Shift
These work like the push and pop operators, but add and subtract from
the beginning of an array rather than the end.
The syntax is
unshift(@arrayname, value);
shift(@arrayname);
Associative Array or Hash
Hashes 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 Netherlan
ds
Key Value
SP Spain
BL Belgium
GE Germany
NL Netherland
s
Perl Command Line
Read from command prompt.
Go to example.
Hash Functions
Assigning : $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'};
Subroutine
Syntax 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
File Management
open(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 / directories
Perl Debugger
Perl -d myprogram.pl
Debugger commands :
l : lists the next few statements.
l 10 : specifies the line number
l 10-15 : display a range of lines
l 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 pattern
S : lists all the subroutines in the file
s : execute single statement and displays next statement to execute
n : same as s command, but n command does not enter subroutine,
directly execute it
r : 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 variable
Resources
Perl.com
Perl.org
Lists.perl.org
Perlmonks
Stackoverflow
Perl mongers
Search.cpan.org
Continued...

Perl

  • 1.
    PERLPERL Practical Extraction &Reporting LanguagePractical Extraction & Reporting Language
  • 2.
    History Developed by LarryWall 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.
  • 3.
    Contents Introduction Variables Operators Conditional Statements andLoops Regular Expressions Subroutines File Handling Many more....
  • 4.
    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
  • 5.
    Introduction Interpreted language, optimizedfor 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.
  • 6.
    Basic Syntax All statementsshould end with ';' # is used for commenting a line Perl is case sensitive Basic options : -c, -v, -w
  • 7.
    Variables Three basic datatypes, scalars, arrays and hashes Scalars : Holds a single value of any type. $var1 = 123 $var2 = “Hello, how r u” $var3 = 1.23 $1var = 123 # Error
  • 8.
    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.
  • 9.
    Control Flow Syntax sameas C If Construct : if (expr) { stmt block; } If Else Construct :
  • 10.
    Loops Loops in Perlare 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) {
  • 11.
    Foreach Behaves same asfor loop. foreach $person (@names) { print "$person"; } $_ : Default Input and Pattern Searching Variable foreach (@names) { print "$_"; }
  • 12.
    Lists List is agroup 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
  • 13.
    Arrays In Perl anarray 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.
  • 14.
    Push, Pop andSplice The 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)
  • 15.
    Unshift and Shift Thesework like the push and pop operators, but add and subtract from the beginning of an array rather than the end. The syntax is unshift(@arrayname, value); shift(@arrayname);
  • 16.
    Associative Array orHash Hashes 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 Netherlan ds Key Value SP Spain BL Belgium GE Germany NL Netherland s
  • 17.
    Perl Command Line Readfrom command prompt. Go to example.
  • 18.
    Hash Functions Assigning :$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'};
  • 19.
    Subroutine Syntax 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
  • 20.
    File Management open(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 / directories
  • 21.
    Perl Debugger Perl -dmyprogram.pl Debugger commands : l : lists the next few statements. l 10 : specifies the line number l 10-15 : display a range of lines l 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 pattern S : lists all the subroutines in the file s : execute single statement and displays next statement to execute n : same as s command, but n command does not enter subroutine, directly execute it r : 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 variable
  • 22.
  • 23.