Perl

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 54

PERL BASICS

Topics Covered
- History and Introduction
- Variables
- Control Structures
- Regular Expression
- File Handling
Introduction
- Practical Extraction and Reporting Language.
- invented by Larry Wall in 1980’s.
- treated as a generic programming language.
- Interpreted language.
- Available as a free Software
Relevance
- Data manipulation
- Glue language : easy to migrate from traditional UNIX tools,tying
together systems & interfaces.
- CGI
- Quick coding
- Portability
Perl program
- Statements:
• they end with a semi colon
• curly braces are required in complex statements
• need not put a wrapping character \ for long statements.

- Comments:
• Anything in a line of Perl code that follows a # sign is a comment.
To run a Perl program
-Type in the example program using a text editor, and save it
as .pl or .cgi
-make sure the file is executable by using the command
chmod u+x progname

-to run the program, just type any of the following at the
prompt.
perl progname
./progname
- You can always run the program with warnings using the
command
perl -w progname

- To run the program with a debugger use the command


perl -d progname

- To check for compilation errrors :


perl –c progname
Integrated Development Environments
(IDEs)

Some good IDEs for Perl:


- Eclipse
- Perl IDE
- Perl Oasis
Perl interpreter
- The perl executable, normally installed in /usr/local/bin on
your machine, is also called the perl interpreter.

#!/usr/bin/perl.

This line gives instructions to the operating system.


pragma
Pragma specifies the rule which perl uses to understand the
code to follow.

- use strict : it enforces the strictest possible rules for


compiling a code.this helps find errors easily.

- use warnings : this tells that the user would like to be


warned as much as possible.it controls the run time
behaviour of the code.
Variables
- variable names consists of numbers, letters and
underscores
- they should not start with a number
- Perl is case sensitive, so $a and $A are different.
There are three different types of variables, each indicated by
its own character,
- $calers,
- @rrays,
- #hashes,
The three types of variables have three separate
namespaces.
That means that $abacus and @abacus are two different
variables.
Scalar
- Scalar variables hold both strings and numbers.
- You don't need to specify whether a scalar is a number or a
string.
- Scalar variables are denoted with $ at the start.
- Example : $age = 27; , $age = 'Seven';
Number variables
- In Perl you can not only specify decimal numbers, but also
numbers in hex, octal, and binary.
But you have to specify when you are going to write a non-
decimal number as:
Binary : 0b, Octal : 0 and Hexadecimal: 0x
- Numbers can be written in exponential form as:
2e-4 = .0002
23e6 = 23,000,000
Operations and Assignment
on Scalars

Numbers

$a = 1 + 2; # Add 1 and 2 and store in $a


$a = 3 - 4; # Subtract 4 from 3 and store in
$a
$a = 5 * 6; # Multiply 5 and 6
$a = 7 / 8; # Divide 7 by 8 to give 0.875
$a = 5 % 2; # Remainder of 5 divided by 2
++$a; # Increment $a and then return it
$a++; # Return $a and then increment it
--$a; # Decrement $a and then return it
$a--; # Return $a and then decrement it
Strings

$a = $b . $c; # Concatenate $b and $c

$a = $b x $c; # $b repeated $c times

Ternary operator
(expr) ? Statement1 : statement2 ;
Perl converts strings to numbers transparently whenever it's
needed as in :

$a = "8"; # Note the quotes. $a is a string.


$b = $a + "1"; # "1" is a string too, $b = 9
$c = $a . "1"; # $c = 81.
To assign values

$a = $b; # Assign $b to $a
$a += $b; # Add $b to $a
$a -= $b; # Subtract $b from $a
$a .= $b; # Append $b onto $a

when Perl assigns a value with $a = $b it makes a copy of


$b and then assigns that to $a. Therefore change in $b it
will not alter $a.
- String literals in perl can be put either in single quotes or in
double quotes.
- Unlike a double quoted string, a single quoted string
expresses exactly what you type in. This is also reffered as
interpolation in double quoted strings.
Arrays
- Arrays are lists of scalars.
- Array names begin with @.
- You define arrays by listing their contents in parentheses,
separated by commas:
@food = ("apples", "pears", "eels");
- Perl offers a shortcut for sequential numbers and letters as:
@abc = (a…..z); @num = (1….9);
- The array is accessed by using indices starting from 0 as:
$food[2]
returns eels.

- The @ has changed to a $ because eels is a scalar.


Array assignments

- push(@food, "eggs");
#which pushes eggs onto the end of the array @food.

- push(@food, @morefood); #pushes an array into another.

- To remove the last item from a list and return it use the pop
function:
$grub = pop(@food); # Now $grub = "eels"
# @food now has two elements.
- If an array doesn't exist, by the way, you'll create it when you
try to assign a value to one of its elements.

$winter_months[0] = "December";

# This implicitly creates @winter_months.


Hashes (Associative Arrays)
- they are: a term and a definition, or in more correct
language a key and a value
- Each key in a hash has one and only one corresponding
value.
- The name of a hash begins with a percentage sign, like
%ages = ("Michael Caine", 39,
"Dirty Den", 34, )
- To find the age of people,expression is as:
$ages{"Michael Caine"}; # Returns 39
$ages{"Dirty Den"}; # Returns 34
-@person = keys %ages;
# @person is now (' Michael Caine ', ' Dirty Den ‘)!
-function each returns a two element list of a key and its value
as in:
while (($person, $age) = each(%ages))
{ print "$person is $age\n"; }
Declarations & Scopes
- Dynamic scoping: Dyanamically scoped constructs
are visible globally.

- Lexical scoping: This creates private constructs that


are visible only within their scopes.
Special Variables
- $_ : when you know a function takes arguments
but you don’t see any.
- @_ : to receive a list of arguments inside the sub
routine.
- $0 : Error in last executed command.
- $$ : Current process ID of your script.
Control Structures
- foreach
foreach $morsel (@food)
{ print "$morsel\n";
"Yum yum\n";}

# Visit each item in turn and call it $morsel and prints the lines
given with the print command.
- Testing
$a == $b # Is $a numerically equal to $b?
# Beware: Don't use the = operator.
$a != $b # Is $a numerically unequal to $b?
$a eq $b # Is $a string-equal to $b?
$a ne $b # Is $a string-unequal to $b?
- You can also use logical and, or and not:

($a && $b) # Is $a and $b true?


($a || $b) # Is either $a or $b true?
!($a) # is $a false?
- for:
it has same structure as in C

for (initialise; test; inc)


{ first_action;
second_action;
# etc }
- while (expression)
{
statement
}
- Until (expression)
{
statement
}
- do:
do {
statement
} while (expression)
do {
statement
} until (expression)
- if-else
if (expression)
{
statement 1
}
else
{
statement 2
}
if (expression)
{
statement 1 }
elsif (expression2)
{
statement 2 }
else (expression 3)
{
statement 3 }
- Last : terminates the loop and exits out of it.

- Next : starts iteration back from top after evaluating


condition.

- Redo : starts iteration back from top without evaluating


condition.
Regular expressions

- Regular expressions are tools for complex searching of


text, considered one of the most powerful aspects of the
Perl language.
- A regular expression is contained in slashes, and matching
occurs with the =~ operator as in :
$Haystack =~ /needle/;
#This returns 1 if "needle" is contained within $HayStack, or
0 otherwise.
- $Haystack =~ /needle/i; # The i means "case-
insensitive“
- $Haystack =~ /(needle|pin)/; # Either/Or statements
- $Haystack =~ /needle \d/; # "needle 0" to "needle
9"
-Regular expression can also be used to modify strings.
$msg = "perl is ok";
$msg =~ s/ok/awesome/;
# search for the word "ok" and replace it with "awesome“

- Putting a g (global) at the end, means it replaces all


occurances and not just the first
$Text =~ s/search for/replace with/g;
- some special RE characters and their meaning :
. # 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
- Some other options:

[qjk] # Either q or j or k
[^qjk] # Neither q nor j nor k
[a-z] # Anything from a to z inclusive
[^a-z] # No lower case letters
[a-zA-Z] # Any letter
[a-z]+ # Any non-zero sequence of lower case letters
Regular Expression Operators
- Match a string
# Shorthand form uses // to quote the regular expression
$Text =~ /search words/;

- Split a string into parts


# The split function allows you to split a string wherever a
regular expression is matched
@ArrayOfParts = split( /,/, $Text); # Splits wherever a
comma is found
@ArrayOfParts = split( /\s+/, $Text); # Splits where
whitespace is found
Some String Functions
- substr() function:
$a = "Welcome to Perl!\n";
print substr($a, 0, 7); # "Welcome"
print substr($a, 7); # " to Perl!\n"
print substr($a, -6, 4); # "Perl

$a = "Welcome to Java!\n";
substr($a, 11, 4) = "Perl"; # $a is now "Welcome to
Perl!\n";
- The join() function
It takes a list of strings and attaches them together with a
specified string between each element, which may be an
empty string:
@a = ("Hello.", "Welcome", "Perl!\n");
$a = join(' ', @a); # "Hello. Welcome Perl!\n";
$b = join(' and ', @a); # "Hello. and Welcome and Perl!\n";
$c = join('', @a); # "Hello.WelcomePerl!\n";
File handling
- Open File.
- Read an opened File.
- Write data into the file.
- Close file.
Open & Read File
- Perl creates a filehandle for you by using the open()
function, which takes two arguments: the filehandle you
want to create and the file you want to work with. as:
open (LOGFILE, "log.txt");

- Once you've opened a file to read, you can retrieve lines


from it by using the <> construct. as:
for $line (<LOGFILE>) { print $line; }
Write into files
- You also use open() when you are writing to a file. There are
two ways to open a file for writing: overwrite and append.

open (OVERWRITE, ">overwrite.txt") or die "$! error ";


# The original contents are gone, wave goodbye.

open (APPEND, ">>append.txt") or die "$! error ";


# Original contents still there, we're adding to the end of the
file

print OVERWRITE "This is the new content.\n";


print APPEND "We're adding to the end here.\n", "And here
too.\n";
die statements
- A series of statements separated by or will continue until
you hit one that works, or returns a true value. This line of
code will either succeed at opening OUTPUT in overwrite
mode, or cause Perl to quit:
open (OUTPUT, ">$outfile") or die "Can't write to
$outfile: $!";

The die statement ends your program with an error message.


The special variable $! contains Perl's explanation of the
error. as in:
Can't write to a2-die.txt: Permission denied at ./a2-die.pl
line 1.
- open (LOG, "log.file") and print "Logfile is open!\n";

#This statement will only show you the words Logfile is open!
if the open() succeeds
Subroutine
- Perl allows the user to define their own functions, called
subroutines. They may be placed anywhere in your
program but it's probably best to put them all at the
beginning or all at the end. A subroutine has the form
sub mysubroutine
{ print "Not a very interesting routine\n";
print "This does the same thing every time\n"; }

-All of the following will work to call this subroutine. Notice that
a subroutine is called with an & character in front of the
name:
&mysubroutine; # Call the subroutine
&mysubroutine($_); # Call it with a parameter
&mysubroutine(1+2, $_); # Call it with two parameters
Returning values
- Result of a subroutine is always the last thing evaluated.
sub maximum
{
if ($_[0] > $_[1])
{ $_[0]; }
else
{ $_[1]; }
}
$biggest = &maximise(37, 24); # Now $biggest is 37
References
- http://en.wikipedia.org/
- http://www.perl.com/
Thank You

You might also like