Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 46

BEGINNING PERL

Written by:
ABHISHEK G. NAIR

GETTING STARTED WITH PERL


Contents
Introduction to Perl
First Steps in Perl
Working with simple values

INTRODUCTION TO PERL
Perl

is a highly popular scripting


language, invented in 1987 by
Larry Wall at NASAs Jet Propulsion
Labs.
Perl is influenced by various
features of other languagespowerful regular expression support
from sed (the UNIX stream editor),
awk (the pattern scanning
language), C, Pascal, BASIC.

WHY PERL?
Perl

emphasizes flexibility and


ease of use: There is more than
one way to do it
Perl is called the Swiss Army
chainsaw knife of programming
languages
Perl is one of the most portable
languages around
Perl features powerful regular
expression support and text

WHERE DO YOU FIND


PERL?
CGI

Scripting
Data transformations
System administration
Network programming
Graphics programming

PERL RESOURCES
On

UNIX systems, use either


perldoc or man to find
information related to commands.
http://www.perl.org- Home to CPAN
http://www.activestate.com- the
source of Perl on Windows.
http://www.strawberryperl.com
Learning Perl, The Perl Cookbook,
Programming Perl published by
OReilly media.

FIRST STEPS WITH PERL


Specify

the problem precisely


Divide and Conquer
Buzzwords:
Compiled/Interpreted; Source
Code; Machine Code/Bytecode;
Editor.

HELLO WORLD
#!/usr/bin/perl w
print Hello World./n
Anything

followed by # is a comment,
except for #!, which is called a
shebang. This tells UNIX where to look
for the Perl interpreter. On Windows, the
location of the Perl interpreter should be
saved as an environment variable.
The w option shows warnings, if any. For
Perl 5.6 and later, write: use warnings;

ADDING ENVIRONMENT
VARIABLES
When

you install the Perl interpreter, it goes into a


particular directory on your computer; on mine, this
is: C:\Strawberry\perl\bin. Hunt this directory out.
Right click on My Computer, click Properties. In
Windows 7, click on Advanced System Settings. On
the window that appears, go to the Advanced tab.
Click on Environment Variables. Edit the variable
PATH (click on PATH and then click Edit).
At the end, add a semicolon followed by the
directory in which the Perl interpreter resides. Click
OK to save changes.
Do not delete anything which is already there in the
PATH variable, or your system may not work.

Keywords-

words understood by the Perl interpreter


Statements- lines in a program that tell the Perl
interpreter something
Functions- executable code that does something
Block- a group of statements marked off by braces,
{ and }. Perl does not care for whitespaces.
Parentheses- used to pass different parameters to
a function
Eg:
print Printing , several , strings , at
once\n;

Or
print(This, does, the, same, as
above\n);

The syntax below is cleaner.

ESCAPE SEQUENCES
\n

gives you a new line.


\t gives you a horizontal tab; \v is
a vertical tab.
\b backs up one character.
\a sounds a bell.
\x{1F18} prints a Unicode
character. 1F18 is a hexadecimal
number in the Unicode set.

NUMBER SYSTEMS
Octal

numbers are designated by


preceding them with 0 (zero).
print(01101) would print 577 (1101 in base 8).
Hexadecimal numbers are designated by
preceding them with 0x (zero-x).
print(0x1101) would print 4353 (1101 in base
16)
print(0xBEEF) would print 48879
Binary numbers are designated by
preceding them with 0b.

VARIABLES
A

variable, as opposed to a
constant, is a placeholder for
data that may change.
Variables in Perl may be scalars,
lists or hashes.
Scalars are of two kindsnumbers and strings.
Numbers could either be integers
or floats.

PRINTING NUMBERS
#!/bin/usr/perl
use warnings;
use strict;
print(25,-4);
What do you think is the output? How
do you change it?

PRINTING NUMBERS
You could write:
#!/bin/usr/perl
use warnings;
use strict;
print(25_000_000, ,-4, \n);
The underscores are ignored by Perl
and are only for readability.

FLOATING POINT
NUMBERS
Just

like integers, floating point


numbers are also represented in
binary form internally.
However, for non-terminating
fractions or other perfectly okay
fractions, there could be an error.
For eg, 0.2 in binary would be
0.001100110011
Therefore, in programming,
floating points cannot be

What do you think the following


code will do?
#!/usr/bin/perl;
use warnings;
use strict;
print(255,"\n");
print(0377,"\n");
print(0b11111111,"\n");
print(0xFF,"\n");

And this one?


#!/usr/bin/perl;
use warnings;
use strict;
print(255,"\n");
print(0378,"\n");
print(0b11111112,"\n");
print(0xFG,"\n");

STRINGS
Strings

are series of characters.


They may contain ASCII or
Unicode data or escape sequence
characters.
Perl does not impose a limit on
the length of a string (other than
that imposed by your computers
memory).
Double quoted strings and Single
quoted strings- no interpolation is

print(This is a double quoted


string.\n);
The output would be:
This is a double quoted string (Return)
whereas:
print(This is a single quoted
string\n);
would give:
This is a single quoted string\n
Note the difference in how \n is treated. We say that in single
quoted strings, the string is not interpolated.

Single quoted strings can be used where

backslashes \ are not to be processed. e.g.


Windows directory names.
Backslashes can also be turned off by a
process called backwhacking. In this, you
simply escape the sequence with another
backslash. e.g. In regular expressions, a dot
(.), which has special meaning can be
escaped by typing \.

print("C:\\Windows\\System\\\n");

would print:
C:\Windows\System\

What would:
print('C:\Windows\System\',"\n");

and:
print('ex\\ er\\','ci\' se\'',"\n");

print?

QUOTATION MARKS
There is no problem with putting single quotes

inside double quotes and putting double quotes


inside single quotes (no interpolation).
print("It's

as easy as that.\n");

would print:
It's as easy as that.(Return)
print('"Stop,"

he cried.',"\n");

would print:
Stop, he cried. (Return)

How would you print:


Hi, said Jack, have you read
the paper today?

inside both single and double quotes?

ALTERNATIVE DELIMITERS
You can use qq// and q/

to limit your string


within double quotes and single quotes,
respectively (You can see the usage inside a
IDE with color formatting)
You can also define your own delimiters,
provided theyre non-alphanumeric. For
instance, {}, [], (), or any other key can be used
as delimiters.
These are used in regular expressions.

HERE-DOCUMENT
You can also place a large amount of text within

your program by using the here-document.


print<<EOF;

<place large text here>


EOF
<< is mandatory; EOF is the label.
By default, the here-document works like a

double quoted string. To make it single quoted,


surround it with single quotes.

CONVERTING BETWEEN STRINGS


and NUMBERS
Perl converts between strings and numbers internally. If

you take a string literal like 0.25 and multiply it by 4,


Perl will output 1.
However, this is not followed for octal and hex numbers.
Octal and Hex numbers within quotes are treated as
strings.
To treat them as numbers, use the functions oct() and
hex().
For these functions, the prefixes 0x and 0 are not
necessary. Thus, it can be noted that strings and
numbers are treated equivalently.

CONVERTING BETWEEN STRINGS


and NUMBERS
Furthermore, these functions stop reading

when they come to a digit that is invalid in the


respective number system. E.g. oct(138) will
give the number 11.
For binary numbers, there is no bin() function,
but you can use oct() with any number, if you
provide the proper prefix. E.g. oct(0b11) will
give you 3.

OPERATORS IN PERL
Perl performs calculations and manipulations using either

functions or operators. Perl doesnt distinguish much between


them- both take operands, process them and return a value.
Operators (numeric) are of 3 kinds- arithmetic, bitwise and
logical.
Arithmetic operators are +, -, * and /. / and * share the same
order of precedence and are followed by +, -.
The precedence can be altered, of course, by using brackets.
The function print() is also an operator, and works to prints its
arguments to the screen. It returns 1 if it is successful, and 0
otherwise.

MORE OPERATORS
**- the exponentiation operator. Raises a

number to a power.
-, the unary minus operator. Negates the
operand.
The modulo operator, %, returns the
remainder of a division. It has the same
precedence as the / and * operators.

BITWISE OPERATORS
Bitwise operators process bits. On numbers, they

work from right (the LSB) to left (MSB).


The bitwise AND (&) takes two bits and returns the
logical AND function. 51 & 85 would give 17 (why?).
AND is associative, since the order of operands
does not matter.
Bitwise OR (|) performs logical OR on two bits at a
time. 204 | 85 would give 221 (why?)
The bitwise XOR (^) operator
The bitwise NOT (~) operator

What happens with the following code:


print(NOT 85 is, ~85);

The output is:


NOT 85 is 4294967210

LOGICAL OPERATORS
Logical operators work on TRUE and FALSE.

These are also called Boolean operators.


== compares two numbers for equality. If the test
fails, Perl returns an empty string. It is not zero,
although if it is used in math, it will be converted so.
The other operators are >, <, <= and >=
A special operator exists, which is <=>. It is like a
balance that points towards the smaller of two
numbers. 6 <=> 7 will give -1; 7 < = > 6 will give 1;
7 < = > 7 will give 0.

OTHER LOGICAL
OPERATORS
&& and || perform logical AND and logical OR

respectively. These should be used whenever true and


false conditions are to be evaluated.
! negates the value of a logical expression; it is like the
NOT operator for a bit.
You can also use and, or, not and xor (one or the
other, but not both). Xor does not have a symbolic sign.
Lazy evaluation
print "Test One: ",6 > 3 && 3 > 4,"\n";
print "Test Two: ",6 > 3 and 3 > 4;

STRING OPERATORS
Concatenation operator .- It works just like ,

but it is better when variables are used.


The repetition operator x repeats a string a
given number of times.
The x precedes . but it has the same
precedence as the arithmetic operators.
print("Ba"."na"x3,"\n");
print("Ba"."na"x3*4,"\n");

What would the following code do?


print("12 monkeys" + 0 , "\n");
print("Eleven to fly" + 0,"\n");
print("UB40" + 0,"\n");
print("0x30" + 0,"\n");

STRING COMPARISON
To compare the values of two characters, we

can use the ord() function which returns the


ASCII value of the character.
To compare strings, we can use lt, gt, cmp, le,
ge, eq.
If we use the relational operators ==, !=, we
may get unexpected results.

PRECEDENCE LIST OF
OPERATORS

VARIABLES
Scalar Variables begin with a $ (this is called a

sigil). A
value, either numeric or string, is put in the variable with a
= (assignment operator).
The assignment operator has very low operator; everything
on its right is evaluated and put into what is on its left.
Modifying a variable is easy; just assign something
different into it.
Modifying and assigning at once is also possible, using the
shorthand which is popular in C:
a = a <operator> b;
a <operator>= b;

AUTOINCREMENT/DECREMENT
++ and -- operators work differently when they

precede a operand than when they succeed.


When they succeed, the assignment happens
first, then the increment/decrement.
When they precede, the increment/decrement
happens first, then the assignment.

MULTIPLE ASSIGNMENTS
$a = $b = $c = 1;

a, b, c are all set to 1.


$b = $a + 4 = 1;

Does not work, because addition is not allowed on


the left of an assignment.
$b = 4 + ($a = 1);

Would work, but is considered bad practice for


readability sake.

SCOPING
Scoping refers to the visibility of a variable.

Variables can be global, meaning they can be


accessed/modified anywhere, or they can be
local, meaning only a certain portion of code
can access it and/or modify it e.g. a subroutine.
Inside the block, you have to use the keyword
my to create a new lexical variable.
Global variables are declared using the ours
keyword.

RULES FOR VARIABLE NAMING


They have to begin with a sigil, $.
After that, a letter (caps or smalls) or an

underscore (_) may follow.


A maximum of 251 characters is allowed for a
variable name.
Perl is case sensitive. $user is different from
$USER and $User.
Spaces and hyphens are not allowed.

INTERPOLATION
Interpolation of variable names occurs only in

double quoted strings, not in single quoted


strings.
If the interpolation is to be limited to just the
variable name, place the variable name in
brackets. e.g. ${name}th will replace the
output with whatever value was placed in
$name, followed immediately by th.

ASSIGNMENT 1
Write a program to ask the user for a

hexadecimal number and converts it into


decimal. Use the STDIN utility to read the user
input.
Syntax:
my $string;
$string = <STDIN>;

ASSIGNMENT 1
Without using Perl, work out the values of the

following expressions:
(1) 2+6/4-3*5+1
(2) 17+-3**3/2
(3) 26+3^4*2
(4) 4+3>=7||2&4*2<4

You might also like