first steps in perl
TRANSCRIPT
What is PERL
PERL stands for Practical Extraction and Report Language.
PERL is a programming language specially designed for text processing
Can be used for system administration, web development, network programming, GUI development, and more.
B Chari K
PERL Features
Perl takes the best features from other languages, such as C, sh, and BASIC, among others.
Perl supports both procedural and object-oriented programming.
Perl is an interpreted language.
Perl program, first compiled into byte code, which then compiled to machine instructions
B Chari K
PERL Basics
Can make perl files self executable by making first line as #! /bin/perl.
Perl files must be saved with .pl or .PL
All commands have to end with “;” Pound sign ‘#’ is the symbol for comment entry
There is no multi line comment entry in perl
B Chari K
PERL Basics
Whitespaces Perl doesn’t care about
whitespaces
Single and Double quotes Only double quotes
interpolate variables and special characters
But single single quotes does not interpolate
B Chari K
PERL Basics
Print command used
to print any thing in between double quotes or single quotes
Perl uses Backslash character to escape any meta character to print
B Chari K
HERE Documents
Can store or print multiline text with the ‘here’ document
Can make use of variables inside ‘here’ document
$var = <<“EOF”
B Chari K
Variables
To store the values there are three types of variables
Scalar variable preceded by sign “ $ “ Array variable preceded by “ @ “ Hash variable preceded by “ % “
Can store integers, decimals, or strings in these variables.
Can use the same name for scalar, array, hash.
$foo and @foo are different variables
B Chari K
Scalar ($)
Scalar is a single unit of data.
$str = “string”; Can do scalar
arithmatic operations
B Chari K
Array (@)
Stores an ordered list of scalar values @arr =
(“one”,”two”,”three”) The index starts from
zero.
To refer single element of an array, will use $ with the varialble name.
B Chari K
Slice and Replace array elements
Can extract an elements from an array
Splice() function removes the elements, replace them with list
splice [@array, offset [ , length [ , list ] ]
Hash ( % )
Hashes are like arrays
Hash preceded by “%”
To refer to a single element of a hash, hash variable name preceded by a "$" followed by the "key" associated with the value in curly brackets
A hash is a set of key/value pairs
B Chari K
Extracting Keys and Values
Can get a list of keys using ‘keys’ function
Keys = %HASH
Can get a values using ‘values’ function
Values = %HASH
B Chari K
Getting User input
Ex:
$input = <STDIN>
Print “you entered : $input”
STDIN accepts the input from keyboard
B Chari K
If
If..else
If..elseif..else
Unless
Unless..else
Unless..elsif..else
switch
Conditional Statements
B Chari K
Conditional Statements
If (boolean_expression) {
# statement(s) will execute if the given condition is true
} else {
# statement(s) will execute if the given condition is false
}
Unless (boolean_expression) {
# statement(s) will execute if the given condition is false
} else {
# statement(s) will execute if the given condition is true
}
B Chari K
Example : Conditional
If..else
$a = 100;
if ( $a < 20 ) {
printf "a is less than 20\n";
else {
printf "a is greater than 20\n";
}
print "value of a is : $a\n";
Unless..else $a = 100;
unless ($a == 20 ) {
printf "given condition is false\n";
} else {
printf "given condition is true\n";
}
print "value of a is : $a\n";
B Chari K
Example : loops
While
Syntax
while(condition) { statement(s); }
Example
$a = 10;
while( $a < 20 ){
printf "Value of a: $a\n";
$a = $a + 1; }
Until Syntax
until(condition) { statement(s); }
Example
$a = 5;
until( $a > 10 ) {
printf "Value of a: $a\n";
$a = $a + 1; }
B Chari K
Example : loops
For Loop
Syntax
for ( init; condition; increment ){ statement(s); }
Example
for( $a = 10; $a < 20; $a = $a + 1 ){
print "value of a: $a\n"; }
Foreach
Syntax
foreach var (list) { ... }
Example
@list = (2, 20, 30, 40, 50);
foreach $a (@list){
print "value of a: $a\n"; }
B Chari K
define and call a Subroutine
To define a subroutine
sub subroutine_name{
body of the subroutine }
To call a subroutine
subroutine_name( list of arguments );
Example
# Function definition
sub Hello{
print "Hello, World!\n"; }
# Function call
Hello();
B Chari K
Passing Arguments to subroutine
#!/usr/bin/perl
# Function definition
sub Average{
# get total number of arguments passed.
$n = scalar(@_);
$sum = 0;
foreach $item (@_){
$sum += $item; }
$average = $sum / $n;
return $average;
print "Average for the given numbers : $average\n"; }
# Function call
Average(10, 20, 30);
The arguments accessed
inside the function using
“@_”
B Chari K
Passing lists to subroutines
#!/usr/bin/perl
# Function definition
sub PrintList{
my @list = @_;
print "Given list is @list\n";
}
$a = 10;
@b = (1, 2, 3, 4);
# Function call with list parameter
Print list($a, @b);
The my operator confines
a variable to a particular
region of code
B Chari K
Operators
Arithmatic Operators
Numeric Equality Operators
String Equality Operators
Assignment Operators
B Chari K
Arithmatic Operators
$c = $a + $b
$c = $a - $b
$c = $a * $b
$c = $a / $b
$c = $a % $b
$c = $a ** $b
B Chari K
Numeric Equality Operators
If ( $a == $b ) { … } If ( $a != $b ) { … } $c = $a <=> $b
If ( $a > $b ) { … } If ( $a >= $b ) { … } If ( $a < $b ) { … } If ( $a <= $b ) { … }
== Equal
=! Not equal
<=> returns -1 0 1 if less than, equal, greater than
> Greater than
< Less than
>= greater than or equal
<= less than or equal
B Chari K
String Equality Operators
if( $a lt $b ) { … }
if( $a gt $b) { … } if( $a le $b ) { … } if( $a ge $b ) { … } if( $a ne $b ) { … }
Lt less than
Gt greater than
Le less than or equal
Ge greater than or equal
Ne not equal
B Chari K
Assignment Operators
Operator Example
= (simple assignment) $c = $a + $b will assigned value of $a + $b into $c
+= (Add and assignment) $c += $a is equivalent to $c = $c + $a
-= (Subtract and assignment) $c -= $a is equivalent to $c = $c - $a
*= (Multiply and assignment) $c *= $a is equivalent to $c = $c * $a
/= (Divide and assignment) $c /= $a is equivalent to $c = $c / $a
%= (Modulus and assignment) $c %= $a is equivalent to $c = $c % a
**= (Exponent and assignment) $c **= $a is equivalent to $c = $c ** $a
B Chari K
File Handle
An internal Perl structure that associates a physical file with a name.
Basic File handles are
STDIN
STDOUT
STDERR
File handles are capable for read/write access
B Chari K
Opening and Closing Files
Open Function
open FILEHANDLE, EXPR
Ex: open(DATA, "<file.txt");
open(DATA, "+<file.txt");
open DATA, "+>file.txt“ open(DATA,">>file.txt")
open(DATA,"+>>file.txt“ Close Function
close FILEHANDLE
Entity Definition
< or r Read
> or w Create, write, truncate
>> or a Writes, appends, creates
+< or r+ Reads and writes
+> or w+
Reads, writes and truncates
+>> or a+
Reads, writes appends and creates
B Chari K
Reading and Writing Files
$name = <DATA>
Returns a single line from the file.
@lines = <DATA>
Returns a list of lines from handle.
getc <STDIN>
Returns a single characters
B Chari K
Copying Files
open(DATA1, "<file1.txt");
open(DATA2, ">file2.txt");
while(<DATA1>) {
print DATA2 $_;
}
close( DATA1 );
close( DATA2 );
B Chari K
Rename and Delete files
Rename the files
rename (“/usr/test/file1.txt", “usr/test/file2.txt" );
Delete the files
unlink ("/usr/test/file1.txt");
B Chari K
Directories
Display files
$dir = "/dir/*";
@files = glob( $dir );
print “@files”;
Creates New directory
$dir = "/dir1/perl";
mkdir( $dir )
Removes a directory
$dir = "/dir1/perl";
rmdir( $dir )
Changes a directory
$dir = "/dir1/perl";
rmdir( $dir )
B Chari K
Special Variables
Variable Description
$_ Reading single line from a file
$0 Name of the file currently being used.
$[ Index of the first element in the array.
$] Version of perl being used.
@_ All the parameters passed from subroutine.
@ARGV Command line arguments passed to the program
$< User id of the process
B Chari K
Regular Expressions
Binding Operators ( ~= )
Match Regular Expressions ( m// )
Substitute Regular Expressions ( s ///)
Translation Regular Expressions ( tr /// )
B Chari K
Match Operator , ( m// )
m/pattern/igxo
Ex:
$bar = "This is you and again
you";
if ($bar =~ /you/i ) {
print "matching\n";
} else {
print "not matching\n"; }
Modifier Description
i Match case insensitive
g Globally finds all matches
x Allows whitespace in expression
o Evaluates expression only once
used to match a string or statement to a regular expression.
B Chari K
Regular Expression variables
Variable Description
$ Contains last group match
$& Entire match
$` everything before matched
$’ Everything after matched
Ex: $string = “This is you and again you"; $string =~ m/you/;
print "Before: $`\n";
print "Matched: $&\n";
print "After: $'\n";
B Chari K
Substitution Operator ( s/// )
Allows to replace the text matched with the new text.
Ex:
$string = “This is you and
again you";
$string =~ s/you/me/;
print "$string\n";
Modifier Description
i Match case insensitive
g Globally finds all matches
x Allows whitespace in expression
o Evaluates expression only once
B Chari K
Translation Operator ( tr/// )
Tr/searchlist/replacementlist/cds
Ex:
$string = ‘this is me and again me';
$string =~ tr/m/h/;
print "$string\n";
Modifier Descriptions
c Complements search list
d Deletes found but unreplaced characters
s Squashes duplicate replaced characters
Replaces all occurances of characters in search list with the corresponding characters in replacement list
B Chari K