Perl Tutorial PDF
Perl Tutorial PDF
Audience
This reference has been prepared for beginners to help them understand the
basic to advanced concepts related to Perl Scripting languages.
Prerequisites
Before you start practicing with various types of examples given in this
reference, we are making an assumption that you have prior exposure to C
programming and Unix Shell.
Table of Contents
About the Tutorial ............................................................................................................................................ i
Audience ........................................................................................................................................................... i
Prerequisites ..................................................................................................................................................... i
Copyright & Disclaimer ..................................................................................................................................... i
Table of Contents ............................................................................................................................................ ii
Introduction .............................................................................................................................................. 2
What is Perl?.................................................................................................................................................... 2
Perl Features.................................................................................................................................................... 2
Perl and the Web ............................................................................................................................................. 3
Perl is Interpreted ............................................................................................................................................ 3
2.
Environment ............................................................................................................................................. 4
Getting Perl Installation ................................................................................................................................... 5
Install Perl ........................................................................................................................................................ 5
Running Perl .................................................................................................................................................... 7
3.
4.
5.
Variables ................................................................................................................................................. 20
Creating Variables ......................................................................................................................................... 20
Scalar Variables ............................................................................................................................................. 21
Array Variables .............................................................................................................................................. 21
Hash Variables ............................................................................................................................................... 22
Variable Context ............................................................................................................................................ 23
6.
Scalars..................................................................................................................................................... 25
Numeric Scalars ............................................................................................................................................. 25
String Scalars ................................................................................................................................................. 26
Scalar Operations .......................................................................................................................................... 27
Multiline Strings ............................................................................................................................................ 27
V-Strings ........................................................................................................................................................ 28
Special Literals ............................................................................................................................................... 29
ii
7.
Arrays ..................................................................................................................................................... 31
Array Creation ............................................................................................................................................... 32
Accessing Array Elements .............................................................................................................................. 32
Sequential Number Arrays ............................................................................................................................ 33
Array Size ....................................................................................................................................................... 34
Adding and Removing Elements in Array ...................................................................................................... 34
Slicing Array Elements ................................................................................................................................... 36
Replacing Array Elements .............................................................................................................................. 37
Transform Strings to Arrays ........................................................................................................................... 37
Transform Arrays to Strings ........................................................................................................................... 38
Sorting Arrays ................................................................................................................................................ 39
The $[ Special Variable .................................................................................................................................. 40
Merging Arrays .............................................................................................................................................. 40
Selecting Elements from Lists ........................................................................................................................ 41
8.
Hashes .................................................................................................................................................... 43
Creating Hashes ............................................................................................................................................. 43
Accessing Hash Elements .............................................................................................................................. 44
Extracting Slices ............................................................................................................................................. 44
Extracting Keys and Values ............................................................................................................................ 45
Checking for Existence ................................................................................................................................... 46
Getting Hash Size ........................................................................................................................................... 47
Add and Remove Elements in Hashes ........................................................................................................... 47
9.
IfElse .................................................................................................................................................... 49
if statement ................................................................................................................................................... 50
if...else statement .......................................................................................................................................... 52
if...elsif...else statement ................................................................................................................................ 54
unless statement ........................................................................................................................................... 55
unless...else statement .................................................................................................................................. 57
unless...elsif..else statement ......................................................................................................................... 59
switch statement ........................................................................................................................................... 60
The ? : Operator ............................................................................................................................................ 63
iii
iv
vi
vii
viii
ix
no................................................................................................................................................................. 404
oct ................................................................................................................................................................ 405
open............................................................................................................................................................. 406
opendir ........................................................................................................................................................ 408
ord ............................................................................................................................................................... 409
our ............................................................................................................................................................... 409
pack ............................................................................................................................................................. 411
package........................................................................................................................................................ 414
pipe .............................................................................................................................................................. 414
pop............................................................................................................................................................... 416
pos ............................................................................................................................................................... 417
print ............................................................................................................................................................. 418
printf ............................................................................................................................................................ 419
prototype..................................................................................................................................................... 422
push ............................................................................................................................................................. 422
q ................................................................................................................................................................... 423
qq................................................................................................................................................................. 424
qr ................................................................................................................................................................. 425
quotemeta ................................................................................................................................................... 426
qw ................................................................................................................................................................ 426
qx ................................................................................................................................................................. 427
rand ............................................................................................................................................................. 428
read ............................................................................................................................................................. 429
readdir ......................................................................................................................................................... 430
readline........................................................................................................................................................ 431
readlink ........................................................................................................................................................ 432
readpipe ...................................................................................................................................................... 433
recv .............................................................................................................................................................. 433
redo ............................................................................................................................................................. 434
ref ................................................................................................................................................................ 435
rename ........................................................................................................................................................ 436
require ......................................................................................................................................................... 437
reset............................................................................................................................................................. 438
return........................................................................................................................................................... 439
reverse ......................................................................................................................................................... 440
rewinddir ..................................................................................................................................................... 441
rindex ........................................................................................................................................................... 443
rmdir ............................................................................................................................................................ 444
s ................................................................................................................................................................... 445
scalar ........................................................................................................................................................... 445
seek.............................................................................................................................................................. 446
seekdir ......................................................................................................................................................... 447
select ........................................................................................................................................................... 448
semctl .......................................................................................................................................................... 449
semget ......................................................................................................................................................... 452
semop .......................................................................................................................................................... 455
send ............................................................................................................................................................. 457
setgrent ....................................................................................................................................................... 458
sethostent.................................................................................................................................................... 461
setnetent ..................................................................................................................................................... 462
setpgrp......................................................................................................................................................... 464
setpriority .................................................................................................................................................... 465
setprotoent .................................................................................................................................................. 466
setpwent ...................................................................................................................................................... 468
setservent .................................................................................................................................................... 471
setsockopt ................................................................................................................................................... 473
shift .............................................................................................................................................................. 474
shmctl .......................................................................................................................................................... 475
shmget ......................................................................................................................................................... 477
shmread ....................................................................................................................................................... 479
shmwrite...................................................................................................................................................... 481
shutdown ..................................................................................................................................................... 483
sin ................................................................................................................................................................ 484
sleep ............................................................................................................................................................ 485
socket .......................................................................................................................................................... 486
socketpair .................................................................................................................................................... 492
sort .............................................................................................................................................................. 493
splice ............................................................................................................................................................ 494
split .............................................................................................................................................................. 495
sprintf .......................................................................................................................................................... 496
sqrt .............................................................................................................................................................. 496
srand ............................................................................................................................................................ 497
stat ............................................................................................................................................................... 498
study ............................................................................................................................................................ 499
sub ............................................................................................................................................................... 500
substr ........................................................................................................................................................... 501
symlink ......................................................................................................................................................... 502
syscall........................................................................................................................................................... 503
sysopen ........................................................................................................................................................ 504
sysread ......................................................................................................................................................... 506
sysseek ......................................................................................................................................................... 506
system ......................................................................................................................................................... 508
syswrite ....................................................................................................................................................... 508
tell ................................................................................................................................................................ 509
telldir ........................................................................................................................................................... 510
tie................................................................................................................................................................. 511
tied............................................................................................................................................................... 514
time ............................................................................................................................................................. 514
times ............................................................................................................................................................ 515
tr .................................................................................................................................................................. 516
truncate ....................................................................................................................................................... 517
uc ................................................................................................................................................................. 517
ucfirst ........................................................................................................................................................... 518
umask .......................................................................................................................................................... 519
undef ........................................................................................................................................................... 520
Description .................................................................................................................................................. 520
unlink ........................................................................................................................................................... 521
unpack ......................................................................................................................................................... 522
unshift.......................................................................................................................................................... 525
untie ............................................................................................................................................................ 525
xi
xii
Perl
1. INTRODUCTION
Perl
What is Perl?
It is used for mission critical projects in the public and private sectors.
At the time of writing this tutorial, the latest version of perl was 5.16.2.
PC Magazine announced Perl as the finalist for its 1998 Technical Excellence
Award in the Development Tool category.
Perl Features
Perl takes the best features from other languages, such as C, awk, sed,
sh, and BASIC, among others.
Perl
Perl is extensible. There are over 20,000 third party modules available
from the Comprehensive Perl Archive Network (CPAN).
Perl used to be the most popular web programming language due to its
text manipulation capabilities and rapid development cycle.
the
Apache
web
server
to
embed
Perl
Perl is Interpreted
Perl is an interpreted language, which means that your code can be run as is,
without a compilation stage that creates a non portable executable program.
Traditional compilers convert programs into machine language. When you run a
Perl program, it's first compiled into a byte code, which is then converted ( as
the program runs) into machine instructions. So it is not quite the same as
shells, or Tcl, which are strictly interpreted without an intermediate
representation.
It is also not like most versions of C or C++, which are compiled directly into a
machine
dependent format.
It
is
somewhere
in
between, along
with Python and awk and Emacs .elc files.
2. ENVIRONMENT
Perl
Before we start writing our Perl programs, let's understand how to setup our Perl
environment. Perl is available on a wide variety of platforms:
Win 9x/NT/2000/
WinCE
OpenVMS
Symbian
Debian GNU/kFreeBSD
MirOS BSD
This is more likely that your system will have perl installed on it. Just try giving
the following command at the $ prompt:
$perl -v
If you have perl installed on your machine, then you will get a message
something as follows:
This is perl 5, version 16, subversion 2 (v5.16.2) built for i686-linux
Perl may be copied only under the terms of either the Artistic License
or the
GNU General Public License, which may be found in the Perl 5 source kit.
Perl
Install Perl
Perl distribution is available for a wide variety of platforms. You need to
download only the binary code applicable for your platform and install Perl.
If the binary code for your platform is not available, you need a C compiler to
compile the source code manually. Compiling the source code offers more
flexibility in terms of choice of features that you require in your installation.
Here is a quick overview of installing Perl on various platforms.
Follow the link to download zipped source code available for Unix/Linux.
Perl
This will install Perl in a standard location /usr/local/bin, and its libraries are
installed in /usr/local/lib/perlXX, where XX is the version of Perl that you are
using.
It will take a while to compile the source code after issuing the make command.
Once installation is done, you can issue perl -v command at $ prompt to check
perl installation. If everything is fine, then it will display message like we have
shown above.
Windows Installation
Here are the steps to install Perl on Windows machine.
Perl
installation
on
Windows
Macintosh Installation
In order to build your own version of Perl, you will need 'make', which is part of
the Apples developer tools usually supplied with Mac OS install DVDs. You do not
need the latest version of Xcode (which is now charged for) in order to install
make.
Here are the simple steps to install Perl on Mac OS X machine.
Follow the link to download zipped source code available for Mac OS X.
Perl
This will install Perl in a standard location /usr/local/bin, and its libraries are
installed in /usr/local/lib/perlXX, where XX is the version of Perl that you are
using.
Running Perl
The following are the different ways to start Perl.
1. Interactive Interpreter
You can enter perl and start coding right away in the interactive interpreter by
starting it from the command line. You can do this from Unix, DOS, or any other
system, which provides you a command-line interpreter or shell window.
$perl
-e <perl code>
# Unix/Linux
or
# Windows/DOS
Description
-d[:debugger]
-Idirectory
-T
-t
-U
-w
-W
-X
Perl
-e program
file
script.pl
# Unix/Linux
or
C:>perl script.pl
# Windows/DOS
3. SYNTAX OVERVIEW
Perl
Perl borrows syntax and concepts from many languages: awk, sed, C, Bourne
Shell, Smalltalk, Lisp and even English. However, there are some definite
differences between the languages. This chapter is designd to quickly get you up
to speed on the syntax that is expected in Perl.
A Perl program consists of a sequence of declarations and statements, which run
from the top to the bottom. Loops, subroutines, and other control structures
allow you to jump around within the code. Every simple statement must end
with a semicolon (;).
Perl is a free-form language: you can format and indent it however you like.
Whitespace serves mostly to separate tokens, unlike languages like Python
where it is an important part of the syntax, or Fortran where it is immaterial.
Perl
priviledge, generally a setting of 0755 works perfectly and finally you execute
the above script as follows:
$chmod 0755 hello.pl
$./hello.pl
This execution will produce the following result:
Hello, world
You can use parentheses for functions arguments or omit them according to
your personal taste. They are only required occasionally to clarify the issues of
precedence. Following two statements produce the same result.
print("Hello, world\n");
print "Hello, world\n";
Comments in Perl
Comments in any programming language are friends of developers. Comments
can be used to make program user friendly and they are simply skipped by the
interpreter without impacting the code functionality. For example, in the above
program, a line starting with hash # is a comment.
Simply saying comments in Perl start with a hash symbol and run to the end of
the line:
# This is a comment in perl
Lines starting with = are interpreted as the start of a section of embedded
documentation (pod), and all subsequent lines until the next =cut are ignored by
the compiler. Following is the example:
#!/usr/bin/perl
10
Perl
=begin comment
This is all part of multiline comment.
You can use as many lines as you like
These comments will be ignored by the
compiler until the next =cut is encountered.
=cut
This will produce the following result:
Hello, world
Whitespaces in Perl
A Perl program does not care about whitespaces. Following program works
perfectly fine:
#!/usr/bin/perl
"Hello, world\n";
But if spaces are inside the quoted strings, then they would be printed as is. For
example:
#!/usr/bin/perl
Perl
whitespace, possibly with a comment, is known as a blank line, and Perl totally
ignores it.
$a = 10;
print "Value of a = $a\n";
print 'Value of a = $a\n';
This will produce the following result:
Value of a = 10
Value of a = $a\n$
"Here" Documents
You can store or print multiline text with a great comfort. Even you can make
use of variables inside the "here" document. Below is a simple syntax, check
carefully there must be no space between the << and the identifier.
An identifier may be either a bare word or some quoted text like we used EOF
below. If identifier is quoted, the type of quote you use determines the
12
Perl
treatment of the text inside the here docoment, just as in regular quoting. An
unquoted identifier works like double quotes.
#!/usr/bin/perl
$a = 10;
$var = <<"EOF";
This is the syntax for here document and it will continue
until it encounters a EOF in the first line.
This is case of double quote so variable value will be
interpolated. For example value of a = $a
EOF
print "$var\n";
$var = <<'EOF';
This is case of single quote so variable value will not be
interpolated. For example value of a = $a
EOF
print "$var\n";
This will produce the following result:
This is the syntax for here document and it will continue
until it encounters a EOF in the first line.
This is case of double quote so variable value will be
interpolated. For example value of a = 10
Escaping Characters
Perl uses the backslash (\) character to escape any type of character that might
interfere with our code. Let's take one example where we want to print double
quote and $ sign:
#!/usr/bin/perl
13
Perl
Perl Identifiers
A Perl identifier is a name used to identify a variable, function, class, module, or
other object. A Perl variable name starts with either $, @ or % followed by zero
or more letters, underscores, and digits (0 to 9).
Perl does not allow punctuation characters such as @, $, and % within
identifiers.
Perl
is
a
case
sensitive programming
language.
Thus $Manpower and $manpower are two different identifiers in Perl.
14
Perl
15
4. DATA TYPES
Perl
Perl is a loosely typed language and there is no need to specify a type for your
data while using in your program. The Perl interpreter will choose the type based
on the context of the data itself.
Perl has three basic data types: scalars, arrays of scalars, and hashes of scalars,
also known as associative arrays. Here is a little detail about these data types.
S.N.
1
Arrays:
Arrays are ordered lists of scalars that you access with a numeric index,
which starts with 0. They are preceded by an "at" sign (@).
Hashes:
Hashes are unordered sets of key/value pairs that you access using the
keys as subscripts. They are preceded by a percent sign (%).
Numeric Literals
Perl stores all the numbers internally as either signed integers or doubleprecision floating-point values. Numeric literals are specified in any of the
following floating-point or integer formats:
Type
Value
Integer
1234
Negative integer
-100
16
Perl
Floating point
2000
Scientific notation
16.12E14
Hexadecimal
0xffff
Octal
0577
String Literals
Strings are sequences of characters. They are usually alphanumeric values
delimited by either single (') or double (") quotes. They work much like UNIX
shell quotes where you can use single quoted strings and double quoted strings.
Double-quoted string literals allow variable interpolation, and single-quoted
strings are not. There are certain characters when they are proceeded by a back
slash, have special meaning and they are used to represent like newline (\n) or
tab (\t).
You can embed newlines or any of the following Escape sequences directly in
your double quoted strings:
Escape sequence
Meaning
\\
Backslash
\'
Single quote
\"
Double quote
\a
Alert or bell
\b
Backspace
\f
Form feed
\n
Newline
\r
Carriage return
17
Perl
\t
Horizontal tab
\v
Vertical tab
\0nn
\xnn
\cX
\u
\l
\U
\L
\Q
\E
Example
Let's see again how strings behave with single quotation and double quotation.
Here we will use string escapes mentioned in the above table and will make use
of the scalar variable to assign string values.
#!/usr/bin/perl
18
Perl
19
5. VARIABLES
Perl
Variables are the reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning
different data types to variables, you can store integers, decimals, or strings in
these variables.
We have learnt that Perl has the following three basic data types:
Scalars
Arrays
Hashes
Creating Variables
Perl variables do not have to be explicitly declared to reserve memory space.
The declaration happens automatically when you assign a value to a variable.
The equal sign (=) is used to assign values to variables.
Keep a note that this is mandatory to declare a variable before we use it if we
use use strict statement in our program.
The operand to the left of the = operator is the name of the variable, and the
operand to the right of the = operator is the value stored in the variable. For
example:
$age = 25;
# An integer assignment
# A string
$salary = 1445.50;
# A floating point
20
Perl
Here
25,
"John
Paul"
and
1445.50
are
the
values
assigned
to $age, $name and $salaryvariables, respectively. Shortly we will see how we
can assign values to arrays and hashes.
Scalar Variables
A scalar is a single unit of data. That data might be an integer number, floating
point, a character, a string, a paragraph, or an entire web page. Simply saying it
could be anything, but only a single thing.
Here is a simple example of using scalar variables:
#!/usr/bin/perl
$age = 25;
# An integer assignment
# A string
$salary = 1445.50;
# A floating point
Array Variables
An array is a variable that stores an ordered list of scalar values. Array variables
are preceded by an "at" (@) sign. To refer to a single element of an array, you
will use the dollar sign ($) with the variable name followed by the index of the
element in square brackets.
Here is a simple example of using array variables:
#!/usr/bin/perl
Perl
Hash Variables
A hash is a set of key/value pairs. Hash variables are preceded by a percent
(%) sign. To refer to a single element of a hash, you will use the hash variable
name followed by the "key" associated with the value in curly brackets.
Here is a simple example of using hash variables:
#!/usr/bin/perl
Perl
$data{'Kumar'} = 40
Variable Context
Perl treats same variable differently based on Context, i.e., situation where a
variable is being used. Let's check the following example:
#!/usr/bin/perl
@copy = @names;
$size = @names;
List:
Assignment to an array or a hash evaluates the right-hand side in a list
context.
23
Perl
Boolean:
Boolean context is simply any place where an expression is being
evaluated to see whether it's true or false.
Void:
This context not only doesn't care what the return value is, it doesn't
even want a return value.
Interpolative:
This context only happens inside quotes, or things that work like quotes.
24
6. SCALARS
Perl
A scalar is a single unit of data. That data might be an integer number, floating
point, a character, a string, a paragraph, or an entire web page.
Here is a simple example of using scalar variables:
#!/usr/bin/perl
$age = 25;
# An integer assignment
# A string
$salary = 1445.50;
# A floating point
Numeric Scalars
A scalar is most often either a number or a string. Following example
demonstrates the usage of various types of numeric scalars:
#!/usr/bin/perl
$integer = 200;
$negative = -300;
$floating = 200.340;
$bigfloat = -1.2E-23;
Perl
$octal = 0377;
String Scalars
Following example demonstrates the usage of various types of string scalars.
Notice the difference between single quoted strings and double quoted strings:
#!/usr/bin/perl
Perl
Scalar Operations
You will see a detail of various operators available in Perl in a separate chapter,
but here we are going to list down few numeric and string operations.
#!/usr/bin/perl
# Concatenates strings.
$num = 5 + 10;
$mul = 4 * 5;
Multiline Strings
If you want to introduce multiline strings into your programs, you can use the
standard single quotes as below:
#!/usr/bin/perl
27
Perl
$string = 'This is
a multiline
string';
print "$string\n";
This will produce the following result:
This is
a multiline
string
You can use "here" document syntax as well to store or print multilines as
below:
#!/usr/bin/perl
print <<EOF;
This is
a multiline
string
EOF
This will also produce the same result:
This is
a multiline
string
V-Strings
A literal of the form v1.20.300.4000 is parsed as a string composed of
characters with the specified ordinals. This form is known as v-strings.
A v-string provides an alternative and more readable way to construct strings,
rather
than
use
the
somewhat
less
readable
interpolation
form
"\x{1}\x{14}\x{12c}\x{fa0}".
They are any literal that begins with a v and is followed by one or more dotseparated elements. For example:
28
Perl
#!/usr/bin/perl
$smile
= v9786;
$foo
= v102.111.111;
$martin = v77.97.114.116.105.110;
Special Literals
So far you must have a feeling about string scalars and its concatenation and
interpolation opration. So let me tell you about three special literals __FILE__,
__LINE__, and __PACKAGE__ represent the current filename, line number, and
package name at that point in your program.
They may be used only as separate tokens and will not be interpolated into
strings. Check the below example:
#!/usr/bin/perl
Perl
Line Number 4
Package main
__FILE__ __LINE__ __PACKAGE__
30
7. ARRAYS
Perl
An array is a variable that stores an ordered list of scalar values. Array variables
are preceded by an "at" (@) sign. To refer to a single element of an array, you
will use the dollar sign ($) with the variable name followed by the index of the
element in square brackets.
Here is a simple example of using the array variables:
#!/usr/bin/perl
31
Perl
Array Creation
Array variables are prefixed with the @ sign and are populated using either
parentheses or the qw operator. For example:
@array = (1, 2, 'Hello');
@array = qw/This is an array/;
The second line uses the qw// operator, which returns a list of strings,
separating the delimited string by white space. In this example, this leads to a
four-element array; the first element is 'this' and last (fourth) is 'array'. This
means that you can use different lines as follows:
@days = qw/Monday
Tuesday
...
Sunday/;
You can also populate an array by assigning each value individually as follows:
$array[0] = 'Monday';
...
$array[6] = 'Sunday';
print "$days[0]\n";
print "$days[1]\n";
print "$days[2]\n";
print "$days[6]\n";
print "$days[-1]\n";
print "$days[-7]\n";
32
Perl
@var_10 = (1..10);
@var_20 = (10..20);
@var_abc = (a..z);
print "@var_10\n";
print "@var_20\n";
print "@var_abc\n";
Here double dot (..) is called range operator. This will produce the following
result:
1 2 3 4 5 6 7 8 9 10
10 11 12 13 14 15 16 17 18 19 20
a b c d e f g h i j k l m n o p q r s t u v w x y z
33
Perl
Array Size
The size of an array can be determined using the scalar context on the array the returned value will be the number of elements in the array:
@array = (1,2,3);
print "Size: ",scalar @array,"\n";
The value returned will always be the physical size of the array, not the number
of valid elements. You can demonstrate this, and the difference between scalar
@array and $#array, using this fragment is as follows:
#!/uer/bin/perl
@array = (1,2,3);
$array[50] = 4;
$size = @array;
$max_index = $#array;
print "Size:
$size\n";
in an
have
other
other
34
Perl
pop @ARRAY
Pops off and returns the last value of the array.
shift @ARRAY
Shifts the first value of the array off and returns it, shortening the array
by 1 and moving everything down.
#!/usr/bin/perl
= @coins\n";
= @coins\n";
= @coins\n";
= @coins\n";
Perl
= @coins\n";
@weekdays = @days[3,4,5];
print "@weekdays\n";
This will produce the following result:
Thu Fri Sat
The specification for a slice must have a list of valid indices, either positive or
negative, each separated by a comma. For speed, you can also use the .. range
operator:
#!/usr/bin/perl
@weekdays = @days[3..5];
print "@weekdays\n";
This will produce the following result:
36
Perl
@nums = (1..20);
print "Before - @nums\n";
splice(@nums, 5, 5, 21..25);
print "After - @nums\n";
This will produce the following result:
Before - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
After - 1 2 3 4 5 21 22 23 24 25 11 12 13 14 15 16 17 18 19 20
Here, the actual replacement begins with the 6th number after that five
elements are then replaced from 6 to 10 with the numbers 21, 22, 23, 24 and
25.
37
Perl
# define Strings
$var_string = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$var_names = "Larry,David,Roger,Ken,Michael,Tom";
= split(',', $var_names);
print "$string[3]\n";
print "$names[4]\n";
# define Strings
$var_string = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$var_names = "Larry,David,Roger,Ken,Michael,Tom";
= split(',', $var_names);
Perl
print "$string1\n";
print "$string2\n";
This will produce the following result:
Rain-Drops-On-Roses-And-Whiskers-On-Kittens
Larry,David,Roger,Ken,Michael,Tom
Sorting Arrays
The sort() function sorts each element of an array according to the ASCII
Numeric standards. This function has the following syntax:
sort [ SUBROUTINE ] LIST
This function sorts the LIST and returns the sorted array value. If SUBROUTINE
is specified then specified logic inside the SUBTROUTINE is applied while sorting
the elements.
#!/usr/bin/perl
# define an array
@foods = qw(pizza steak chicken burgers);
print "Before: @foods\n";
39
Perl
# define an array
@foods = qw(pizza steak chicken burgers);
print "Foods: @foods\n";
Merging Arrays
Because an array is just a comma-separated sequence of values, you can
combine them together as shown below:
#!/usr/bin/perl
@numbers = (1,3,(4,5,6));
40
Perl
@odd = (1,3,5);
@even = (2, 4, 6);
$var = (5,4,3,2,1)[4];
Perl
@list = (5,4,3,2,1)[1..3];
42
8. HASHES
Perl
Creating Hashes
Hashes are created in one of the two following ways. In the first method, you
assign a value to a named key on a one-by-one basis:
$data{'John Paul'} = 45;
$data{'Lisa'} = 30;
$data{'Kumar'} = 40;
In the second case, you use a list, which is converted by taking individual pairs
from the list: the first element of the pair is used as the key, and the second, as
the value. For example:
%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);
For clarity, you can use => as an alias for , to indicate the key/value pairs as
follows:
43
Perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
Here is one more variant of the above form, have a look at it, here all the keys
have been preceded by hyphen (-) and no quotation is required around them:
%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40);
But it is important to note that there is a single word, i.e., without spaces keys
have been used in this form of hash formation and if you build-up your hash this
way then keys will be accessed using hyphen only as shown below.
$val = %data{-JohnPaul}
$val = %data{-Lisa}
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
Extracting Slices
You can extract slices of a hash just as you can extract slices from an array. You
will need to use @ prefix for the variable to store the returned value because
they will be a list of values:
#!/uer/bin/perl
44
Perl
%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40);
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
print "$names[0]\n";
print "$names[1]\n";
print "$names[2]\n";
This will produce the following result:
Lisa
John Paul
Kumar
Similarly, you can use values function to get a list of all the values. This function
has the following syntax:
45
Perl
values %HASH
This function returns a normal array consisting of all the values of the named
hash. Following is the example:
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
print "$ages[0]\n";
print "$ages[1]\n";
print "$ages[2]\n";
This will produce the following result:
30
45
40
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
if( exists($data{'Lisa'} ) ){
print "Lisa is $data{'Lisa'} years old\n";
}
else{
print "I don't know age of Lisa\n";
46
Perl
}
Here we have introduced the IF...ELSE statement, which we will study in a
separate chapter. For now you just assume that if( condition ) part will be
executed only when the given condition is true otherwise else part will be
executed. So when we execute the above program, it produces the following
result because here the given condition exists($data{'Lisa'} returns true:
Lisa is 30 years old
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
is $size\n";
is $size\n";
Perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@keys = keys %data;
$size = @keys;
print "1 - Hash size:
is $size\n";
is $size\n";
is $size\n";
48
Perl
9. IFELSE
Perl conditional statements helps in the decision making, which require that the
programmer specifies one or more conditions to be evaluated or tested by the
program, along with a statement or statements to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
Following is the general from of a typical decision making structure found in
most of the programming languages:
The number 0, the strings '0' and "" , the empty list () , and undef are
all false in a boolean context and all other values are true. Negation of a true
value by ! or not returns a special false value.
Perl programming
statements.
language
provides
Statement
the
following
types
of
conditional
Description
if statement
An if
statement consists
of
a
boolean
expression followed by one or more statements.
if...else statement
An if
statement can
be
followed
by
an
49
Perl
unless statement
unless...else statement
unless...elsif..else statement
switch statement
by
by
an
an
if statement
A Perl if statement consists of a boolean expression followed by one or more
statements.
Syntax
The syntax of an if statement in Perl programming language is:
if(boolean_expression){
# statement(s) will execute if the given condition is true
}
If the boolean expression evaluates to true then the block of code inside the if
statement will be executed. If boolean expression evaluates to false then the
first set of code after the end of the if statement (after the closing curly brace)
will be executed.
The number 0, the strings '0' and "" , the empty list () , and undef are
all false in a boolean context and all other values are true. Negation of a true
value by ! or not returns a special false value.
50
Perl
Flow Diagram
Example
#!/usr/local/bin/perl
$a = 10;
# check the boolean condition using if statement
if( $a < 20 ){
# if condition is true then print the following
printf "a is less than 20\n";
}
print "value of a is : $a\n";
$a = "";
# check the boolean condition using if statement
if( $a ){
# if condition is true then print the following
printf "a has a true value\n";
}
print "value of a is : $a\n";
51
Perl
First IF statement makes use of less than operator (<), which compares two
operands and if first operand is less than the second one then it returns true
otherwise it returns false. So when the above code is executed, it produces the
following result:
a is less than 20
value of a is : 10
value of a is :
if...else statement
A Perl if statement can be followed by an optional else statement, which
executes when the boolean expression is false.
Syntax
The syntax of an if...else statement in Perl programming language is:
if(boolean_expression){
# statement(s) will execute if the given condition is true
}else{
# statement(s) will execute if the given condition is false
}
If the boolean expression evaluates to true, then the if block of code will be
executed otherwise else block of code will be executed.
The number 0, the strings '0' and "" , the empty list () , and undef are
all false in a boolean context and all other values are true. Negation of a true
value by ! or not returns a special false value.
52
Perl
Flow Diagram
Example
#!/usr/local/bin/perl
$a = 100;
# check the boolean condition using if statement
if( $a < 20 ){
# if condition is true then print the following
printf "a is less than 20\n";
}else{
# if condition is false then print the following
printf "a is greater than 20\n";
}
print "value of a is : $a\n";
$a = "";
# check the boolean condition using if statement
if( $a ){
# if condition is true then print the following
printf "a has a true value\n";
53
Perl
}else{
# if condition is false then print the following
printf "a has a false value\n";
}
print "value of a is : $a\n";
When the above code is executed, it produces the following result:
a is greater than 20
value of a is : 100
a has a false value
value of a is :
if...elsif...else statement
An if statement can be followed by an optional elsif...else statement, which is
very useful to test the various conditions using single if...elsif statement.
When using if , elsif , else statements there are few points to keep in mind.
An if can have zero or one else's and it must come after any elsif's.
An if can have zero to many elsif's and they must come before the else.
Syntax
The syntax of an if...elsif...else statement in Perl programming language is:
if(boolean_expression 1){
# Executes when the boolean expression 1 is true
}
elsif( boolean_expression 2){
# Executes when the boolean expression 2 is true
}
elsif( boolean_expression 3){
# Executes when the boolean expression 3 is true
}
else{
54
Perl
Example
#!/usr/local/bin/perl
$a = 100;
# check the boolean condition using if statement
if( $a
==
20 ){
30 ){
unless statement
A Perl unless statement consists of a boolean expression followed by one or
more statements.
Syntax
The syntax of an unless statement in Perl programming language is:
unless(boolean_expression){
# statement(s) will execute if the given condition is false
}
55
Perl
If the boolean expression evaluates to false, then the block of code inside the
unless statement will be executed. If boolean expression evaluates to true then
the first set of code after the end of the unless statement (after the closing curly
brace) will be executed.
The number 0, the strings '0' and "" , the empty list () , and undef are
all false in a boolean context and all other values are true. Negation of a true
value by ! or not returns a special false value.
Flow Diagram
Example
#!/usr/local/bin/perl
$a = 20;
# check the boolean condition using unless statement
unless( $a < 20 ){
# if condition is false then print the following
printf "a is not less than 20\n";
}
print "value of a is : $a\n";
$a = "";
# check the boolean condition using unless statement
56
Perl
unless ( $a ){
# if condition is false then print the following
printf "a has a false value\n";
}
print "value of a is : $a\n";
First unless statement makes use of less than operator (<), which compares two
operands and if first operand is less than the second one then it returns true
otherwise it returns false. So when the above code is executed, it produces the
following result:
a is not less than 20
value of a is : 20
a has a false value
value of a is :
unless...else statement
A Perl unless statement can be followed by an optional else statement, which
executes when the boolean expression is true.
Syntax:
The syntax of an unless...else statement in Perl programming language is:
unless(boolean_expression){
# statement(s) will execute if the given condition is false
}else{
# statement(s) will execute if the given condition is true
}
If the boolean expression evaluates to true then the unless block of code will
be executed otherwise else block of code will be executed.
The number 0, the strings '0' and "" , the empty list () , and undef are
all false in a boolean context and all other values are true. Negation of a true
value by ! or not returns a special false value.
57
Perl
Flow Diagram
Example
#!/usr/local/bin/perl
$a = 100;
# check the boolean condition using unless statement
unless( $a == 20 ){
# if condition is false then print the following
printf "given condition is false\n";
}else{
# if condition is true then print the following
printf "given condition is true\n";
}
print "value of a is : $a\n";
$a = "";
# check the boolean condition using unless statement
unless( $a ){
# if condition is false then print the following
printf "a has a false value\n";
58
Perl
}else{
# if condition is true then print the following
printf "a has a true value\n";
}
print "value of a is : $a\n";
When the above code is executed, it produces the following result:
given condition is false
value of a is : 100
a has a false value
value of a is :
unless...elsif..else statement
An unless statement can be followed by an optional elsif...else statement,
which is very useful to test the various conditions using single unless...elsif
statement.
When using unless, elsif, else statements there are few points to keep in mind.
An unless can have zero or one else's and it must come after any elsif's.
An unless can have zero to many elsif's and they must come before the
else.
Syntax
The syntax of an unless...elsif...else statement in Perl programming language
is:
unless(boolean_expression 1){
# Executes when the boolean expression 1 is false
}
elsif( boolean_expression 2){
# Executes when the boolean expression 2 is true
}
elsif( boolean_expression 3){
# Executes when the boolean expression 3 is true
59
Perl
}
else{
# Executes when the none of the above condition is met
}
Example
#!/usr/local/bin/perl
$a = 20;
# check the boolean condition using if statement
unless( $a
==
30 ){
30 ){
switch statement
A switch statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is
checked for each switch case.
A
switch
case
implementation
is
dependent
on Switch module
and Switch module
has
been
implemented
using Filter::Util::Call and Text::Balanced and requires both these modules to be
installed.
60
Perl
Syntax
The synopsis for a switch statement in Perl programming language is as follows:
use Switch;
switch(argument){
case 1
case "a"
case [1..10,42]
case (\@array)
case /\w+/
{ print "pattern" }
case qr/\w+/
{ print "pattern" }
case (\%hash)
case (\&sub)
else
}
The following rules apply to a switch statement:
The value is followed by a block, which may contain one or more case
statement followed by a block of Perl statement(s).
If the match is successful, the mandatory block associated with the case
statement is executed.
A switch statement can have an optional else case, which must appear at
the end of the switch. The default case can be used for performing a task
when none of the cases is matched.
Not every case needs to contain a next. If no next appears, the flow of
control will not fall through subsequent cases.
61
Perl
Flow Diagram
Example
#!/usr/local/bin/perl
use Switch;
$var = 10;
@array = (10, 20, 30);
%hash = ('key1' => 10, 'key2' => 20);
switch($var){
case 10
case "a"
case [1..10,42]
case (\@array)
case (\%hash)
else
Perl
}
When the above code is executed, it produces the following result:
number 100
Fall-though is usually a bad idea in a switch statement. However, now consider a
fall-through case, we will use the next to transfer the control to the next
matching case, which is a list in this case:
#!/usr/local/bin/perl
use Switch;
$var = 10;
@array = (10, 20, 30);
%hash = ('key1' => 10, 'key2' => 20);
switch($var){
case 10
case "a"
case [1..10,42]
case (\@array)
case (\%hash)
else
}
When the above code is executed, it produces the following result:
number 100
number in list
The ? : Operator
Let's check the conditional operator ? : which can
replace if...else statements. It has the following general form:
be
used
to
63
Perl
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of
the colon.
The value of a ? expression is determined like this: Exp1 is evaluated. If it is
true, then Exp2 is evaluated and becomes the value of the entire ? expression. If
Exp1 is false, then Exp3 is evaluated and its value becomes the value of the
expression. Below is a simple example making use of this operator:
#!/usr/local/bin/perl
$name = "Ali";
$age = 10;
print "$name is
- $status\n";
64
10. LOOPS
Perl
There may be a situation when you need to execute a block of code several
number of times. In general, statements are executed sequentially: The first
statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements
multiple times and following is the general form of a loop statement in most of
the programming languages:
Perl programming language provides the following types of loop to handle the
looping requirements.
Loop Type
Description
while loop
until loop
Perl
foreach loop
do...while loop
nested loops
while loop
A while loop statement in Perl programming language repeatedly executes a
target statement as long as a given condition is true.
Syntax
The syntax of a while loop in Perl programming language is:
while(condition)
{
statement(s);
}
Here statement(s) may be a single statement or a block of statements.
The condition may be any expression. The loop iterates while the condition is
true. When the condition becomes false, program control passes to the line
immediately following the loop.
The number 0, the strings '0' and "" , the empty list () , and undef are
all false in a boolean context and all other values are true. Negation of a true
value by ! or not returns a special false value.
66
Perl
Flow Diagram
Here the key point of the while loop is that the loop might not ever run. When
the condition is tested and the result is false, the loop body will be skipped and
the first statement after the while loop will be executed.
Example
#!/usr/local/bin/perl
$a = 10;
Perl
Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15
Value of a: 16
Value of a: 17
Value of a: 18
Value of a: 19
until loop
An until loop statement in Perl programming language repeatedly executes a
target statement as long as a given condition is false.
Syntax
The syntax of an until loop in Perl programming language is:
until(condition)
{
statement(s);
}
Here statement(s) may be a single statement or a block of statements.
The condition may be any expression. The loop iterates until the condition
becomes true. When the condition becomes true, the program control passes to
the line immediately following the loop.
The number 0, the strings '0' and "" , the empty list () , and undef are
all false in a boolean context and all other values are true. Negation of a true
value by ! or not returns a special false value.
68
Perl
Flow Diagram
Here key point of the until loop is that the loop might not ever run. When the
condition is tested and the result is true, the loop body will be skipped and the
first statement after the until loop will be executed.
Example
#!/usr/local/bin/perl
$a = 5;
Perl
greater than 10, it comes out. When executed, above code produces the
following result:
Value of a: 5
Value of a: 6
Value of a: 7
Value of a: 8
Value of a: 9
Value of a: 10
for loop
A for loop is a repetition control structure that allows you to efficiently write a
loop that needs to execute a specific number of times.
Syntax
The syntax of a for loop in Perl programming language is:
for ( init; condition; increment ){
statement(s);
}
Here is the flow of control in a for loop:
1. The init step is executed first, and only once. This step allows you to
declare and initialize any loop control variables. You are not required to
put a statement here, as long as a semicolon appears.
2. Next, the condition is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow of
control jumps to the next statement just after the for loop.
3. After the body of the for loop executes, the flow of control jumps back up
to the increment statement. This statement allows you to update any
loop control variables. This statement can be left blank, as long as a
semicolon appears after the condition.
4. The condition is now evaluated again. If it is true, the loop executes and
the process repeats itself (body of loop, then increment step, and then
again condition). After the condition becomes false, the for loop
terminates.
70
Perl
Flow Diagram
Example
#!/usr/local/bin/perl
Perl
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
foreach loop
The foreach loop iterates over a list value and sets the control variable (var) to
be each element of the list in turn:
Syntax
The syntax of a foreach loop in Perl programming language is:
foreach var (list) {
...
}
72
Perl
Flow Diagram
Example
#!/usr/local/bin/perl
Perl
do...while loop
Unlike for and while loops, which test the loop condition at the top of the loop,
the do...while loop checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time.
Syntax
The syntax of a do...while loop in Perl is:
do
{
statement(s);
}while( condition );
It should be noted that the conditional expression appears at the end of the
loop, so the statement(s) in the loop executes once before the condition is
tested. If the condition is true, the flow of control jumps back up to do, and the
statement(s) in the loop executes again. This process repeats until the given
condition becomes false.
The number 0, the strings '0' and "" , the empty list () , and undef are
all false in a boolean context and all other values are true. Negation of a true
value by ! or not returns a special false value.
Flow Diagram
74
Perl
Example
#!/usr/local/bin/perl
$a = 10;
nested loops
A loop can be nested inside of another loop. Perl allows to nest all type of loops
to be nested.
Syntax
The syntax for a nested for loop statement in Perl is as follows:
for ( init; condition; increment ){
for ( init; condition; increment ){
statement(s);
}
75
Perl
statement(s);
}
The syntax for a nested while loop statement in Perl is as follows:
while(condition){
while(condition){
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in Perl is as follows:
do{
statement(s);
do{
statement(s);
}while( condition );
}while( condition );
The syntax for a nested until loop statement in Perl is as follows:
until(condition){
until(condition){
statement(s);
}
statement(s);
}
The syntax for a nested foreach loop statement in Perl is as follows:
foreach $a (@listA){
foreach $b (@listB){
statement(s);
}
statement(s);
76
Perl
Example
The following program uses a nested while loop to show the usage:
#/usr/local/bin/perl
$a = 0;
$b = 0;
value of a = 1, b = 0
value of a = 1, b = 1
value of a = 1, b = 2
Value of a = 2
value of a = 2, b = 0
value of a = 2, b = 1
77
Perl
value of a = 2, b = 2
Value of a = 3
Description
next statement
last statement
continue statement
redo statement
goto statement
next statement
The Perl next statement starts the next iteration of the loop. You can provide a
LABEL with next statement where LABEL is the label for a loop.
A next statement can be used inside a nested loop where it will be applicable to
the nearest loop if a LABEL is not specified.
If there is a continue block on the loop, it is always executed just before the
condition is about to be evaluated. You will see the continue statement in
separate chapter.
78
Perl
Syntax
The syntax of a next statement in Perl is:
next [ LABEL ];
A LABEL inside the square braces indicates that LABEL is optional and if a LABEL
is not specified, then next statement will jump the control to the next iteration of
the nearest loop.
Flow Diagram
Example
#!/usr/local/bin/perl
$a = 10;
while( $a < 20 ){
if( $a == 15)
{
# skip the iteration.
$a = $a + 1;
next;
}
print "value of a: $a\n";
79
Perl
$a = $a + 1;
}
When the above code is executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Let's take one example where we are going to use a LABEL along with next
statement:
#!/usr/local/bin/perl
$a = 0;
OUTER: while( $a < 4 ){
$b = 0;
print "value of a: $a\n";
INNER:while ( $b < 4){
if( $a == 2){
$a = $a + 1;
# jump to outer loop
next OUTER;
}
$b = $b + 1;
print "Value of b : $b\n";
}
print "\n";
$a = $a + 1;
}
80
Perl
value of a: 1
Value of b : 1
Value of b : 2
Value of b : 3
Value of b : 4
value of a: 2
value of a: 3
Value of b : 1
Value of b : 2
Value of b : 3
Value of b : 4
last statement
When a last statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the
loop. You can provide a LABEL with last statement where LABEL is the label for a
loop. A last statement can be used inside a nested loop where it will be
applicable to the nearest loop if a LABEL is not specified.
If there is any continue block on the loop, then it is not executed. You will see
the continue statement in a separate chapter.
Syntax
The syntax of a last statement in Perl is:
last [LABEL];
81
Perl
Flow Diagram
Example 1
#!/usr/local/bin/perl
$a = 10;
while( $a < 20 ){
if( $a == 15)
{
# terminate the loop.
$a = $a + 1;
last;
}
print "value of a: $a\n";
$a = $a + 1;
}
When the above code is executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
82
Perl
value of a: 13
value of a: 14
Example 2
Let's take one example where we are going to use a LABEL along with next
statement:
#!/usr/local/bin/perl
$a = 0;
OUTER: while( $a < 4 ){
$b = 0;
print "value of a: $a\n";
INNER:while ( $b < 4){
if( $a == 2){
# terminate outer loop
last OUTER;
}
$b = $b + 1;
print "Value of b : $b\n";
}
print "\n";
$a = $a + 1;
}
When the above code is executed, it produces the following result:
value of a: 0
Value of b : 1
Value of b : 2
Value of b : 3
Value of b : 4
value of a: 1
Value of b : 1
Value of b : 2
83
Perl
Value of b : 3
Value of b : 4
value of a: 2
continue statement
A continue BLOCK, is always executed just before the conditional is about to be
evaluated again. A continue statement can be used with while and foreach loops.
A continue statement can also be used alone along with a BLOCK of code in
which case it will be assumed as a flow control statement rather than a function.
Syntax
The syntax for a continue statement with while loop is as follows:
while(condition){
statement(s);
}continue{
statement(s);
}
The syntax for a continue statement with foreach loop is as follows:
foreach $a (@listA){
statement(s);
}continue{
statement(s);
}
The syntax for a continue statement with a BLOCK of code is as follows:
continue{
statement(s);
}
Example
The following program simulates a for loop using a while loop:
#/usr/local/bin/perl
84
Perl
$a = 0;
while($a < 3){
print "Value of a = $a\n";
}continue{
$a = $a + 1;
}
This would produce the following result:
Value of a = 0
Value of a = 1
Value of a = 2
The following program shows the usage of continue statement with foreach
loop:
#/usr/local/bin/perl
redo statement
The redo command restarts the loop block without evaluating the conditional
again. You can provide a LABEL with redo statement where LABEL is the label
for a loop. A redo statement can be used inside a nested loop where it will be
applicable to the nearest loop if a LABEL is not specified.
85
Perl
If there is any continue block on the loop, then it will not be executed before
evaluating the condition.
Syntax
The syntax for a redo statement is as follows:
redo [LABEL]
Flow Diagram
Example
The following program shows the usage of redo statement:
#/usr/local/bin/perl
$a = 0;
while($a < 10){
if( $a == 5 ){
$a = $a + 1;
redo;
}
print "Value of a = $a\n";
}continue{
86
Perl
$a = $a + 1;
}
goto statement
Perl does support a goto statement. There are three forms: goto LABEL, goto
EXPR, and goto &NAME.
S.N.
1
goto type
goto LABEL
The goto LABEL form jumps to the statement labeled with LABEL and
resumes execution from there.
goto EXPR
The goto EXPR form is just a generalization of goto LABEL. It expects
the expression to return a label name and then jumps to that labeled
statement.
goto &NAME
It substitutes a call to the named subroutine for the currently running
subroutine.
Syntax
The syntax for a goto statements is as follows:
goto LABEL
or
goto EXPR
or
goto &NAME
87
Perl
Flow Diagram
Example
The following program shows the most frequently used form of goto statement:
#/usr/local/bin/perl
$a = 10;
LOOP:do
{
if( $a == 15){
# skip the iteration.
$a = $a + 1;
# use goto LABEL form
goto LOOP;
}
print "Value of a = $a\n";
$a = $a + 1;
}while( $a < 20 );
When the above code is executed, it produces the following result:
Value of a = 10
88
Perl
Value of a = 11
Value of a = 12
Value of a = 13
Value of a = 14
Value of a = 16
Value of a = 17
Value of a = 18
Value of a = 19
Following example shows the usage of goto EXPR form. Here we are using two
strings and then concatenating them using string concatenation operator (.).
Finally, its forming a label and goto is being used to jump to the label:
#/usr/local/bin/perl
$a = 10;
$str1 = "LO";
$str2 = "OP";
LOOP:do
{
if( $a == 15){
# skip the iteration.
$a = $a + 1;
# use goto EXPR form
goto $str1.$str2;
}
print "Value of a = $a\n";
$a = $a + 1;
}while( $a < 20 );
When the above code is executed, it produces the following result:
Value of a = 10
Value of a = 11
Value of a = 12
89
Perl
Value of a = 13
Value of a = 14
Value of a = 16
Value of a = 17
Value of a = 18
Value of a = 19
for( ; ; )
{
printf "This loop will run forever.\n";
}
You can terminate the above infinite loop by pressing the Ctrl + C keys.
When the conditional expression is absent, it is assumed to be true. You may
have an initialization and increment expression, but as a programmer more
commonly use the for (;;) construct to signify an infinite loop.
90
Perl
11. OPERATORS
What is an Operator?
Simple answer can be given using the expression 4 + 5 is equal to 9. Here 4 and
5 are called operands and + is called operator. Perl language supports many
operator types, but following is a list of important and most frequently used
operators:
Arithmetic Operators
Equality Operators
Logical Operators
Assignment Operators
Bitwise Operators
Logical Operators
Quote-like Operators
Miscellaneous Operators
Description
Example
$a + $b will give 30
91
Perl
$b / $a will give 2
$b % $a will give 0
**
Example
Try the following example to understand all the arithmatic operators available in
Perl. Copy and paste the following Perl program in test.pl file and execute this
program.
#!/usr/local/bin/perl
$a = 21;
$b = 10;
$c = $a + $b;
print 'Value of $a + $b = ' . $c . "\n";
$c = $a - $b;
print 'Value of $a - $b = ' . $c . "\n";
$c = $a * $b;
print 'Value of $a * $b = ' . $c . "\n";
$c = $a / $b;
print 'Value of $a / $b = ' . $c . "\n";
$c = $a % $b;
print 'Value of $a % $b = ' . $c. "\n";
92
Perl
$a = 2;
$b = 4;
$c = $a ** $b;
print 'Value of $a ** $b = ' . $c . "\n";
When the above code is executed, it produces the following result:
Value of $a = 21 and value of $b = 10
Value of $a + $b = 31
Value of $a - $b = 11
Value of $a * $b = 210
Value of $a / $b = 2.1
Value of $a % $b = 1
Value of $a ** $b = 16
Description
Example
==
!=
<=>
>
93
Perl
>=
<=
Example
Try the following example to understand all the numeric equality operators
available in Perl. Copy and paste the following Perl program in test.pl file and
execute this program.
#!/usr/local/bin/perl
$a = 21;
$b = 10;
if( $a == $b ){
print "$a == \$b is true\n";
}else{
print "\$a == \$b is not true\n";
}
if( $a != $b ){
print "\$a != \$b is true\n";
}else{
print "\$a != \$b is not true\n";
94
Perl
$c = $a <=> $b;
print "\$a <=> \$b returns $c\n";
if( $a > $b ){
print "\$a > \$b is true\n";
}else{
print "\$a > \$b is not true\n";
}
if( $a >= $b ){
print "\$a >= \$b is true\n";
}else{
print "\$a >= \$b is not true\n";
}
if( $a < $b ){
print "\$a < \$b is true\n";
}else{
print "\$a < \$b is not true\n";
}
if( $a <= $b ){
print "\$a <= \$b is true\n";
}else{
print "\$a <= \$b is not true\n";
}
When the above code is executed, it produces the following result:
Value of $a = 21 and value of $b = 10
$a == $b is not true
$a != $b is true
$a <=> $b returns 1
95
Perl
$a > $b is true
$a >= $b is true
$a < $b is not true
$a <= $b is not true
Below is a list of equity operators. Assume variable $a holds "abc" and variable
$b holds "xyz" then, lets check the following string equality operators:
Operator
Description
Example
lt
gt
le
ge
eq
ne
cmp
Example
Try the following example to understand all the string equality operators
available in Perl. Copy and paste the following Perl program in test.pl file and
execute this program.
#!/usr/local/bin/perl
$a = "abc";
96
Perl
$b = "xyz";
if( $a lt $b ){
print "$a lt \$b is true\n";
}else{
print "\$a lt \$b is not true\n";
}
if( $a gt $b ){
print "\$a gt \$b is true\n";
}else{
print "\$a gt \$b is not true\n";
}
if( $a le $b ){
print "\$a le \$b is true\n";
}else{
print "\$a le \$b is not true\n";
}
if( $a ge $b ){
print "\$a ge \$b is true\n";
}else{
print "\$a ge \$b is not true\n";
}
if( $a ne $b ){
print "\$a ne \$b is true\n";
}else{
print "\$a ne \$b is not true\n";
}
97
Perl
$c = $a cmp $b;
print "\$a cmp \$b returns $c\n";
When the above code is executed, it produces the following result:
Value of $a = abc and value of $b = xyz
abc lt $b is true
$a gt $b is not true
$a le $b is true
$a ge $b is not true
$a ne $b is true
$a cmp $b returns -1
Description
Example
$c = $a + $b will
assigned value of $a +
$b into $c
+=
$c += $a is equivalent
to $c = $c + $a
-=
$c -= $a is equivalent
to $c = $c - $a
*=
$c *= $a is equivalent
to $c = $c * $a
98
Perl
/=
$c /= $a is equivalent
to $c = $c / $a
%=
$c %= $a is equivalent
to $c = $c % a
**=
$c
**=
$a
is
equivalent to $c = $c
** $a
Example
Try the following example to understand all the assignment operators available
in Perl. Copy and paste the following Perl program in test.pl file and execute this
program.
#!/usr/local/bin/perl
$a = 10;
$b = 20;
$c = $a + $b;
print "After assignment value of \$c = $c\n";
$c += $a;
print "Value of \$c = $c after statement \$c += \$a\n";
$c -= $a;
print "Value of \$c = $c after statement \$c -= \$a\n";
$c *= $a;
print "Value of \$c = $c after statement \$c *= \$a\n";
99
Perl
$c /= $a;
print "Value of \$c = $c after statement \$c /= \$a\n";
$c %= $a;
print "Value of \$c = $c after statement \$c %= \$a\n";
$c = 2;
$a = 4;
print "Value of \$a = $a and value of \$c = $c\n";
$c **= $a;
print "Value of \$c = $c after statement \$c **= \$a\n";
When the above code is executed, it produces the following result:
Value of $a = 10 and value of $b = 20
After assignment value of $c = 30
Value of $c = 40 after statement $c += $a
Value of $c = 30 after statement $c -= $a
Value of $c = 300 after statement $c *= $a
Value of $c = 30 after statement $c /= $a
Value of $c = 0 after statement $c %= $a
Value of $a = 4 and value of $c = 2
Value of $c = 16 after statement $c **= $a
Perl
Description
Example
&
<<
>>
Example
Try the following example to understand all the bitwise operators available in
Perl. Copy and paste the following Perl program in test.pl file and execute this
program.
#!/usr/local/bin/perl
use integer;
$a = 60;
101
Perl
$b = 13;
$c = $a & $b;
print "Value of \$a & \$b = $c\n";
$c = $a | $b;
print "Value of \$a | \$b = $c\n";
$c = $a ^ $b;
print "Value of \$a ^ \$b = $c\n";
$c = ~$a;
print "Value of ~\$a = $c\n";
$c = $a << 2;
print "Value of \$a << 2 = $c\n";
$c = $a >> 2;
print "Value of \$a >> 2 = $c\n";
When the above code is executed, it produces the following result:
Value of $a = 60 and value of $b = 13
Value of $a & $b = 12
Value of $a | $b = 61
Value of $a ^ $b = 49
Value of ~$a = 18446744073709551555
Value of $a << 2 = 240
Value of $a >> 2 = 15
102
Perl
Description
Example
and
&&
or
||
not
not($a
true.
and
$b)
is
Example
Try the following example to understand all the logical operators available in
Perl. Copy and paste the following Perl program in test.pl file and execute this
program.
#!/usr/local/bin/perl
$a = true;
$b = false;
Perl
$c = ($a
&& $b);
$c = ($a or $b);
print "Value of \$a or \$b = $c\n";
$c = ($a || $b);
print "Value of \$a || \$b = $c\n";
$a = 0;
$c = not($a);
print "Value of not(\$a)= $c\n";
When the above code is executed, it produces the following result:
Value of $a = true and value of $b = false
Value of $a and $b = false
Value of $a && $b = false
Value of $a or $b = true
Value of $a || $b = true
Value of not($a)= 1
Quote-like Operators
There are following Quote-like operators supported by Perl language. In the
following table, a {} represents any pair of delimiters you choose.
Operator
Description
Example
q{ }
qq{ }
qq{abcd}
"abcd"
gives
qx{ }
qx{abcd}
gives
104
Perl
`abcd`
Example
Try the following example to understand all the quote-like operators available in
Perl. Copy and paste the following Perl program in test.pl file and execute this
program.
#!/usr/local/bin/perl
$a = 10;
$b = q{a = $a};
print "Value of q{a = \$a} = $b\n";
$b = qq{a = $a};
print "Value of qq{a = \$a} = $b\n";
Miscellaneous Operators
There are following miscellaneous operators supported by Perl language. Assume
variable a holds 10 and variable b holds 20 then:
Operator
.
Description
Example
If $a="abc", $b="def"
then $a.$b will give
"abcdef"
105
Perl
..
++
--
->
decreases
$obj->$a
is
an
example to access
variable
$a
from
object $obj.
Example
Try the following example to understand all the miscellaneous operators
available in Perl. Copy and paste the following Perl program in test.pl file and
execute this program.
#!/usr/local/bin/perl
$a = "abc";
$b = "def";
$c = $a . $b;
print "Value of \$a . \$b = $c\n";
$c = "-" x 3;
print "Value of \"-\" x 3 = $c\n";
106
Perl
@c = (2..5);
print "Value of (2..5) = @c\n";
$a = 10;
$b = 15;
print "Value of \$a
$a++;
$c = $a ;
print "Value of \$a after \$a++ = $c\n";
$b--;
$c = $b ;
print "Value of \$b after \$b-- = $c\n";
When the above code is executed, it produces the following result:
Value of $a = abc and value of $b = def
Value of $a . $b = abcdef
Value of "-" x 3 = --Value of (2..5) = 2 3 4 5
Value of $a = 10 and value of $b = 15
Value of $a after $a++ = 11
Value of $b after $b-- = 14
We will explain --> operator when we will discuss about Perl Object and Classes.
++ --
right
**
right
left =~ !~
107
Perl
left * / % x
left + - .
left << >>
nonassoc
nonassoc
nonassoc
== != <=> eq ne cmp ~~
left &
left | ^
left &&
left || //
nonassoc
..
...
right
?:
right
= += -= *= etc.
left , =>
nonassoc
right
not
left and
left or xor
Example
Try the following example to understand all the perl operators precedence in
Perl. Copy and paste the following Perl program in test.pl file and execute this
program.
#!/usr/local/bin/perl
$a = 20;
$b = 10;
$c = 15;
$d = 5;
$e;
Perl
= $e\n";
= $e\n";
= $e\n";
$e = $a + ($b * $c ) / $d;
print "Value of \$a + (\$b * \$c )/ \$d is
= $e\n";
109
Perl
This chapter will give you the basic understanding on how to process and
manipulate dates and times in Perl.
min,
hour,
mday,
mon,
year,
wday,
yday,
isdst
@months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
@days = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
print "$mday $months[$mon] $days[$wday]\n";
When the above code is executed, it produces the following result:
16 Feb Sat
110
Perl
If you will use localtime() function in scalar context, then it will return date and
time from the current time zone set in the system. Try the following example to
print current date and time in full format:
#!/usr/local/bin/perl
$datestring = localtime();
print "Local date and time $datestring\n";
When the above code is executed, it produces the following result:
Local date and time Sat Feb 16 06:50:45 2013
GMT Time
The function gmtime() works just like localtime() function but the returned
values are localized for the standard Greenwich time zone. When called in list
context, $isdst, the last value returned by gmtime, is always 0. There is no
Daylight Saving Time in GMT.
You should make a note on the fact that localtime() will return the current local
time on the machine that runs the script and gmtime() will return the universal
Greenwich Mean Time, or GMT (or UTC).
Try the following example to print the current date and time but on GMT scale:
#!/usr/local/bin/perl
$datestring = gmtime();
print "GMT date and time $datestring\n";
When the above code is executed, it produces the following result:
GMT date and time Sat Feb 16 13:50:45 2013
111
Perl
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
Epoch time
You can use the time() function to get epoch time, i.e., the numbers of seconds
that have elapsed since a given date, in Unix is January 1, 1970.
#!/usr/local/bin/perl
$epoc = time();
$datestring = localtime();
print "Current date and time $datestring\n";
$epoc = time();
$epoc = $epoc - 12 * 60 * 60;
$datestring = localtime($epoc);
print "Yesterday's date and time $datestring\n";
When the above code is executed, it produces the following result:
112
Perl
Replaced by
Example
%a
Thu
%A
Thursday
%b
Aug
%B
August
%c
Thu
Aug
23
14:55:02 2001
%C
20
%d
23
%D
08/23/01
%e
23
%F
2001-08-23
%g
01
%g
Week-based year
2001
%h
Aug
113
Perl
%H
14
%I
02
%j
235
%m
08
%M
Minute (00-59)
55
%n
%p
AM or PM designation
PM
%r
02:55:02 pm
%R
14:55
%S
Second (00-61)
02
%t
%T
14:55
%u
%U
33
%V
34
%w
%W
34
114
Perl
Date representation *
08/23/01
%X
Time representation *
14:55:02
%y
01
%Y
Year
2001
%z
+100
CDT
A % sign
115
13. SUBROUTINES
Perl
# Function definition
sub Hello{
print "Hello, World!\n";
}
# Function call
116
Perl
Hello();
When above program is executed, it produces the following result:
Hello, World!
# Function definition
sub Average{
# get total number of arguments passed.
$n = scalar(@_);
$sum = 0;
# Function call
Average(10, 20, 30);
117
Perl
# Function definition
sub PrintList{
my @list = @_;
print "Given list is @list\n";
}
$a = 10;
@b = (1, 2, 3, 4);
# Function definition
sub PrintHash{
my (%hash) = @_;
118
Perl
# Function definition
sub Average{
# get total number of arguments passed.
$n = scalar(@_);
$sum = 0;
119
Perl
return $average;
}
# Function call
$num = Average(10, 20, 30);
print "Average for the given numbers : $num\n";
When above program is executed, it produces the following result:
Average for the given numbers : 20
Perl
# Global variable
$string = "Hello, World!";
# Function definition
sub PrintHello{
# Private variable for PrintHello function
my $string;
$string = "Hello, Perl!";
print "Inside the function $string\n";
}
# Function call
PrintHello();
print "Outside the function $string\n";
When above program is executed, it produces the following result:
Inside the function Hello, Perl!
Outside the function Hello, World!
# Global variable
$string = "Hello, World!";
121
Perl
sub PrintHello{
# Private variable for PrintHello function
local $string;
$string = "Hello, Perl!";
PrintMe();
print "Inside the function PrintHello $string\n";
}
sub PrintMe{
print "Inside the function PrintMe $string\n";
}
# Function call
PrintHello();
print "Outside the function $string\n";
When above program is executed, it produces the following result:
Inside the function PrintMe Hello, Perl!
Inside the function PrintHello Hello, Perl!
Outside the function Hello, World!
sub PrintCount{
state $count = 0; # initial value
122
Perl
for (1..5){
PrintCount();
}
When above program is executed, it produces the following result:
Value of counter is 0
Value of counter is 1
Value of counter is 2
Value of counter is 3
Value of counter is 4
Prior to Perl 5.10, you would have to write it like this:
#!/usr/bin/perl
{
my $count = 0; # initial value
sub PrintCount {
print "Value of counter is $count\n";
$count++;
}
}
for (1..5){
PrintCount();
}
Perl
values based on what the user is expecting to receive. For example, the
following localtime() returns a string when it is called in scalar context, but it
returns a list when it is called in list context.
my $datestring = localtime( time );
In this example, the value of $timestr is now a string made up of the current
date and time, for example, Thu Nov 30 15:21:33 2000. Conversely:
($sec,$min,$hour,$mday,$mon, $year,$wday,$yday,$isdst) =
localtime(time);
Now the individual variables contain the corresponding values returned by
localtime() subroutine.
124
14. REFERENCES
Perl
A Perl reference is a scalar data type that holds the location of another value
which could be scalar, arrays, or hashes. Because of its scalar nature, a
reference can be used anywhere, a scalar can be used.
You can construct lists containing references to other lists, which can contain
references to hashes, and so on. This is how the nested data structures are built
in Perl.
Create References
It is easy to create a reference for any variable, subroutine or value by prefixing
it with a backslash as follows:
$scalarref = \$foo;
$arrayref
= \@ARGV;
$hashref
= \%ENV;
$coderef
= \&handler;
$globref
= \*foo;
=> 'Eve',
125
Perl
Dereferencing
Dereferencing returns the value from a reference point to the location. To
dereference a reference simply use $, @ or % as prefix of the reference variable
depending on whether the reference is pointing to a scalar, array, or hash.
Following is the example to explain the concept:
#!/usr/bin/perl
$var = 10;
@$r, "\n";
Perl
SCALAR
ARRAY
HASH
CODE
GLOB
REF
Let's try the following example:
#!/usr/bin/perl
$var = 10;
$r = \$var;
print "Reference type in r : ", ref($r), "\n";
Circular References
A circular reference occurs when two references contain a reference to each
other. You have to be careful while creating references otherwise a circular
reference can lead to memory leaks. Following is an example:
#!/usr/bin/perl
my $foo = 100;
127
Perl
$foo = \$foo;
References to Functions
This might happen if you need to create a signal handler so you can produce a
reference to a function by preceding that function name with \& and to
dereference that reference you simply need to prefix reference variable using
ampersand &. Following is an example:
#!/usr/bin/perl
# Function definition
sub PrintHash{
my (%hash) = @_;
Perl
Item : 19
129
15. FORMATS
Perl
Perl uses a writing template called a 'format' to output reports. To use the
format feature of Perl, you have to define a format first and then you can use
that format to write formatted data.
Define a Format
Following is the syntax to define a Perl format:
format FormatName =
fieldline
value_one, value_two, value_three
fieldline
value_one, value_two
.
Here FormatName represents the name of the format. The fieldline is the
specific way, the data should be formatted. The values lines represent the values
that will be entered into the field line. You end the format with a single period.
Next fieldline can contain any text or fieldholders. The fieldholders hold space
for data that will be placed there at a later date. A fieldholder has the format:
@<<<<
This fieldholder is left-justified, with a field space of 5. You must count the @
sign and the < signs to know the number of spaces in the field. Other field
holders include:
@>>>> right-justified
@|||| centered
@####.## numeric field holder
@* multiline field holder
An example format would be:
format EMPLOYEE =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<<
130
Perl
$name $age
@#####.##
$salary
===================================
.
In this example, $name would be written as left justify within 22 character
spaces and after that age will be written in two spaces.
format EMPLOYEE =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<<
131
Perl
$name $age
@#####.##
$salary
===================================
.
select(STDOUT);
$~ = EMPLOYEE;
= (20,30, 40);
$i = 0;
foreach (@n){
$name = $_;
$age = $a[$i];
$salary = $s[$i++];
write;
}
When executed, this will produce the following result:
===================================
Ali
20
2000.00
===================================
===================================
Raza
30
2500.00
===================================
===================================
Jaffer
40
4000.00
132
Perl
===================================
format EMPLOYEE =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<<
$name $age
@#####.##
$salary
===================================
.
format EMPLOYEE_TOP =
===================================
Name
Age
===================================
.
select(STDOUT);
$~ = EMPLOYEE;
$^ = EMPLOYEE_TOP;
= (20,30, 40);
$i = 0;
133
Perl
foreach (@n){
$name = $_;
$age = $a[$i];
$salary = $s[$i++];
write;
}
Now your report will look like:
===================================
Name
Age
===================================
===================================
Ali
20
2000.00
===================================
===================================
Raza
30
2500.00
===================================
===================================
Jaffer
40
4000.00
===================================
Define a Pagination
What about if your report is taking more than one page? You have a solution for
that, simply use $% or $FORMAT_PAGE_NUMBER vairable along with header as
follows:
format EMPLOYEE_TOP =
===================================
Name
===================================
134
Perl
.
Now your output will look like as follows:
===================================
Name
Age Page 1
===================================
===================================
Ali
20
2000.00
===================================
===================================
Raza
30
2500.00
===================================
===================================
Jaffer
40
4000.00
===================================
135
Perl
For a complete set of variables related to formating, please refer to the Perl
Special Variables section.
136
Perl
The basics of handling files are simple: you associate a filehandle with an
external entity (usually a file) and then use a variety of operators and functions
within Perl to read and update the data stored within the data stream associated
with the filehandle.
A filehandle
a name. All
and update
associate a
opened.
Three basic file handles are - STDIN, STDOUT, and STDERR, which represent
standard input, standard output and standard error devices respectively.
Open Function
Following is the syntax to open file.txt in read-only mode. Here less than < sign
indicates that file has to be opend in read-only mode.
open(DATA, "<file.txt");
Here DATA is the file handle, which will be used to read the file. Here is the
example, which will open a file and will print its content over the screen.
#!/usr/bin/perl
137
Perl
while(<DATA>){
print "$_";
}
Following is the syntax to open file.txt in writing mode. Here less than > sign
indicates that file has to be opend in the writing mode.
open(DATA, ">file.txt") or die "Couldn't open file file.txt, $!";
This example actually truncates (empties) the file before opening it for writing,
which may not be the desired effect. If you want to open a file for reading and
writing, you can put a plus sign before the > or < characters.
For example, to open a file for updating without truncating it:
open(DATA, "+<file.txt"); or die "Couldn't open file file.txt, $!";
To truncate the file first:
open DATA, "+>file.txt" or die "Couldn't open file file.txt, $!";
You can open a file in the append mode. In this mode, writing point will be set to
the end of the file.
open(DATA,">>file.txt") || die "Couldn't open file file.txt, $!";
A double >> opens the file for appending, placing the file pointer at the end, so
that you can immediately start appending information. However, you can't read
from it unless you also place a plus sign in front of it:
open(DATA,"+>>file.txt") || die "Couldn't open file file.txt, $!";
Following is the table, which gives the possible values of different modes
Entities
Definition
< or r
> or w
>> or a
Perl
+< or r+
+> or w+
+>> or a+
Sysopen Function
The sysopen function is similar to the main open function, except that it uses
the system open() function, using the parameters supplied to it as the
parameters for the system function:
For example, to open a file for updating, emulating the +<filename format from
open:
sysopen(DATA, "file.txt", O_RDWR);
Or to truncate the file before updating:
sysopen(DATA, "file.txt", O_RDWR|O_TRUNC );
You can use O_CREAT to create a new file and O_WRONLY- to open file in write
only mode and O_RDONLY - to open file in read only mode.
The PERMS argument specifies the file permissions for the file specified, if it has
to be created. By default it takes 0x666.
Following is the table, which gives the possible values of MODE.
Entities
Definition
O_RDWR
O_RDONLY
Read Only
O_WRONLY
Write Only
O_CREAT
O_APPEND
O_TRUNC
Perl
O_EXCL
O_NONBLOCK
Non-Blocking usability
Close Function
To close a filehandle, and therefore disassociate the filehandle from the
corresponding file, you use the close function. This flushes the filehandle's
buffers and closes the system's file descriptor.
close FILEHANDLE
close
If no FILEHANDLE is specified, then it closes the currently selected filehandle. It
returns true only if it could successfully flush the buffers and close the file.
close(DATA) || die "Couldn't close file properly";
Perl
getc Function
The getc function returns a single character from the specified FILEHANDLE, or
STDIN if none is specified:
getc FILEHANDLE
getc
If there was an error, or the filehandle is at end of file, then undef is returned
instead.
read Function
The read function reads a block of information from the buffered filehandle: This
function is used to read binary data from the file.
read FILEHANDLE, SCALAR, LENGTH, OFFSET
read FILEHANDLE, SCALAR, LENGTH
The length of the data read is defined by LENGTH, and the data is placed at the
start of SCALAR if no OFFSET is specified. Otherwise data is placed after OFFSET
bytes in SCALAR. The function returns the number of bytes read on success,
zero at end of file, or undef if there was an error.
print Function
For all the different methods used for reading information from filehandles, the
main function for writing information back is the print function.
print FILEHANDLE LIST
print LIST
print
The print function prints the evaluated value of LIST to FILEHANDLE, or to the
current output filehandle (STDOUT by default). For example:
print "Hello World!\n";
141
Perl
Copying Files
Here is the example, which opens an existing file file1.txt and read it line by line
and generate another copy file file2.txt.
#!/usr/bin/perl
Renaming a file
Here is an example, which shows how we can rename a file file1.txt to file2.txt.
Assuming file is available in /usr/test directory.
#!/usr/bin/perl
142
Perl
unlink ("/usr/test/file1.txt");
of
file
tell Function
The first requirement is to find your position within a file, which you do using the
tell function:
tell FILEHANDLE
tell
This returns the position of the file pointer, in bytes, within FILEHANDLE if
specified, or the current default selected filehandle if none is specified.
seek Function
The seek function positions the file pointer to the specified number of bytes
within a file:
seek FILEHANDLE, POSITION, WHENCE
The function uses the fseek system function, and you have the same ability to
position relative to three different points: the start, the end, and the current
position. You do this by specifying a value for WHENCE.
Zero sets the positioning relative to the start of the file. For example, the line
sets the file pointer to the 256th byte in the file.
seek DATA, 256, 0;
File Information
You can test certain features very quickly within Perl using a series of test
operators known collectively as -X tests. For example, to perform a quick test of
the various permissions on a file, you might use a script like this:
#/usr/bin/perl
my $file = "/usr/test/file1.txt";
my (@description, $size);
143
Perl
if (-e $file)
{
push @description, 'binary' if (-B _);
push @description, 'a socket' if (-S _);
push @description, 'a text file' if (-T _);
push @description, 'a block special file' if (-b _);
push @description, 'a character special file' if (-c _);
push @description, 'a directory' if (-d _);
push @description, 'executable' if (-x _);
push @description, (($size = -s _)) ? "$size bytes" : 'empty';
print "$file is ", join(', ',@description),"\n";
}
Here is the list of features, which you can check for a file or directory:
Operator
Definition
-A
-B
Is it a binary file?
-C
Script start time minus file last inode change time, in days.
-M
-O
-R
-S
-T
Is it a text file?
-W
-X
Perl
-b
-c
-d
-e
-f
Is it a plain file?
-g
-k
-l
-o
-p
-r
-s
-t
-u
-w
-x
-z
145
17. DIRECTORIES
Perl
# To open a directory
readdir DIRHANDLE
# To read a directory
rewinddir DIRHANDLE
telldir DIRHANDLE
closedir DIRHANDLE
# Closing a directory.
foreach (@files ){
print $_ . "\n";
}
foreach (@files ){
print $_ . "\n";
}
146
Perl
foreach (@files ){
print $_ . "\n";
}
Here is another example, which opens a directory and list out all the files
available inside this directory.
#!/usr/bin/perl
Perl
$dir = "/tmp/perl";
Remove a directory
You can use rmdir function to remove a directory. You will need to have the
required permission to remove a directory. Additionally this directory should be
empty before you try to remove it.
#!/usr/bin/perl
$dir = "/tmp/perl";
Change a Directory
You can use chdir function to change a directory and go to a new location. You
will need to have the required permission to change a directory and go inside
the new directory.
#!/usr/bin/perl
$dir = "/home";
Perl
149
Perl
The execution and the errors always go together. If you are opening a file which
does not exist. then if you did not handle this situation properly then your
program is considered to be of bad quality.
The program stops if an error occurs. So a proper error handling is used to
handle various type of errors, which may occur during a program execution and
take appropriate action instead of halting program completely.
You can identify and trap an error in a number of different ways. Its very easy to
trap errors in Perl and then handling them properly. Here are few methods which
can be used.
The if statement
The if statement is the obvious choice when you need to check the return value
from a statement; for example:
if(open(DATA, $file)){
...
}else{
die "Error: Couldn't open the file - $!";
}
Here variable $! returns the actual error message. Alternatively, we can reduce
the statement to one line in situations where it makes sense to do so; for
example:
open(DATA, $file) || die "Error: Couldn't open the file $!";
Perl
The unless statement is best used when you want to raise an error or
alternative only if the expression fails. The statement also makes sense when
used in a single-line statement:
die "Error: Can't change directory!: $!" unless(chdir("/etc"));
Here we die only if the chdir operation fails, and it reads nicely.
Reporting an error in a module that quotes the module's filename and line
number - this is useful when debugging a module, or when you
specifically want to raise a module-related, rather than script-related,
error.
151
Perl
The warn and die functions work slightly differently than you would expect when
called from within a module. For example, the simple module:
package T;
require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp;
sub function {
warn "Error in module!";
}
1;
When called from a script like below:
use T;
function();
It will produce the following result:
Error in module! at T.pm line 9.
This is more or less what you might expected, but not necessarily what you
want. From a module programmer's perspective, the information is useful
because it helps to point to a bug within the module itself. For an end-user, the
information provided is fairly useless, and for all but the hardened programmer,
it is completely pointless.
The solution for such problems is the Carp module, which provides a simplified
method for reporting errors within modules that return information about the
calling script. The Carp module provides four functions: carp, cluck, croak, and
confess. These functions are discussed below.
152
Perl
require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp;
sub function {
carp "Error in module!";
}
1;
When called from a script like below:
use T;
function();
It will produce the following result:
Error in module! at test.pl line 4
require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp qw(cluck);
153
Perl
sub function {
cluck "Error in module!";
}
1;
When called from a script like below:
use T;
function();
It will produce the following result:
Error in module! at T.pm line 9
T::function() called at test.pl line 4
require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp;
sub function {
croak "Error in module!";
}
1;
When called from a script like below:
use T;
function();
It will produce the following result:
154
Perl
require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp;
sub function {
confess "Error in module!";
}
1;
When called from a script like below:
use T;
function();
It will produce the following result:
Error in module! at T.pm line 9
T::function() called at test.pl line 4
155
Perl
156
Perl
There are some variables which have a predefined and special meaning in Perl.
They are the variables that use punctuation characters after the usual variable
indicator ($, @, or %), such as $_ ( explained below ).
Most of the special variables have an english like long name, e.g., Operating
System Error variable $! can be written as $OS_ERROR. But if you are going to
use english like names, then you would have to put one line use English; at the
top of your program file. This guides the interpreter to pickup exact meaning of
the variable.
The most commonly used special variable is $_, which contains the default input
and pattern-searching string. For example, in the following lines:
#!/usr/bin/perl
foreach ('hickory','dickory','doc') {
print $_;
print "\n";
}
When executed, this will produce the following result:
hickory
dickory
doc
Again, let's check the same example without using $_ variable explicitly:
#!/usr/bin/perl
foreach ('hickory','dickory','doc') {
print;
print "\n";
}
When executed, this will also produce the following result:
hickory
157
Perl
dickory
doc
The first time the loop is executed, "hickory" is printed. The second time around,
"dickory" is printed, and the third time, "doc" is printed. That's because in each
iteration of the loop, the current string is placed in $_, and is used by default by
print. Here are the places where Perl will assume $_ even if you don't specify it:
Various unary functions, including functions like ord and int, as well as the
all file tests (-f, -d) except for -t, which defaults to STDIN.
The pattern-matching operations m//, s///, and tr/// when used without
an =~ operator.
The
default
input
and
pattern158
Perl
$ARG
searching space.
$.
$NR
$/
$RS
$,
$OFS
$\
$ORS
$"
$LIST_SEPARATOR
$;
$SUBSCRIPT_SEPARATOR
$^L
separator
for
array
emulation.
$FORMAT_FORMFEED
$:
$FORMAT_LINE_BREAK_CHARACTERS
$^A
current
value
of
the
write
159
Perl
$ACCUMULATOR
$#
$OFMT
$?
$CHILD_ERROR
$!
$OS_ERROR or $ERRNO
$@
$EVAL_ERROR
$$
$PROCESS_ID or $PID
$<
$REAL_USER_ID or $UID
$>
$EFFECTIVE_USER_ID or $EUID
$(
The real
process.
group
ID
(gid)
of
this
$REAL_GROUP_ID or $GID
$)
Perl
$EFFECTIVE_GROUP_ID or $EGID
$0
$PROGRAM_NAME
of the file
script being
$[
$]
$PERL_VERSION
$^D
$DEBUGGING
$^E
Extended error
platforms.
message
on
some
$EXTENDED_OS_ERROR
$^F
$SYSTEM_FD_MAX
$^H
Contains
internal
compiler
hints
enabled by certain pragmatic modules.
$^I
$INPLACE_EDIT
$^M
Perl
more information.
$^O
$OSNAME
$^P
$PERLDB
$^T
$BASETIME
$^W
$WARNING
$^X
$EXECUTABLE_NAME
$ARGV
@INC
@F
The array into which the input lines are split when the
-a command-line switch is given.
162
Perl
%ENV
%SIG
STDERR
STDIN
STDOUT
DATA
_ (underscore)
Perl
DATA filehandle.
__FILE__
__LINE__
__PACKAGE__
$&
$MATCH
$`
$PREMATCH
$'
$POSTMATCH
$+
$LAST_PAREN_MATCH
164
Perl
$FORMAT_PAGE_NUMBER
$=
$FORMAT_LINES_PER_PAGE
$-
$FORMAT_LINES_LEFT
$~
$FORMAT_NAME
$^
$FORMAT_TOP_NAME
165
Perl
Each programmer will, of course, have his or her own preferences in regards to
formatting, but there are some general guidelines that will make your programs
easier to read, understand, and maintain.
The most important thing is to run your programs under the -w flag at all times.
You may turn it off explicitly for particular portions of code via the no warnings
pragma or the $^W variable if you must. You should also always run under use
strict or know the reason why not. The use sigtrap and even use diagnostics
pragmas may also prove useful.
Regarding aesthetics of code lay out, about the only thing Larry cares strongly
about is that the closing curly bracket of a multi-line BLOCK should line up with
the keyword that started the construct. Beyond that, he has other preferences
that aren't so strong:
4-column indent.
Uncuddled elses.
Here are some other more substantive style issues to think about: Just because
you CAN do something a particular way doesn't mean that you SHOULD do it
166
Perl
that way. Perl is designed to give you several ways to do anything, so consider
picking the most readable one. For instance:
open(FOO,$foo) || die "Can't open $foo: $!";
Is better than die "Can't open $foo: $!" unless open(FOO,$foo);
Because the second way hides the main point of the statement in a modifier. On
the other hand,
print "Starting analysis\n" if $verbose;
Is better than $verbose && print "Starting analysis\n";
Because the main point isn't whether the user typed -v or not.
Don't go through silly contortions to exit a loop at the top or the bottom, when
Perl provides the last operator so you can exit in the middle. Just "outdent" it a
little to make it more visible:
LINE:
for (;;) {
statements;
last LINE if $foo;
next LINE if /^#/;
statements;
}
Let's see few more important points:
Avoid using grep() (or map()) or `backticks` in a void context, that is,
when you just throw away their return values. Those functions all have
return values, so use them. Otherwise use a foreach() loop or the
system() function instead.
Perl
module will also let you interrogate values determined by the Configure
program when Perl was installed.
While short identifiers like $gotit are probably ok, use underscores to
separate words in longer identifiers. It is generally easier to read
$var_names_like_this than $VarNamesLikeThis, especially for non-native
speakers of English. It's also a simple rule that works consistently with
VAR_NAMES_LIKE_THIS.
If you have a really hairy regular expression, use the /x modifier and put
in some whitespace to make it look a little less like line noise. Don't use
slash as a delimiter when your regexp has slashes or backslashes.
Always check the return codes of system calls. Good error messages
should go to STDERR, include which program caused the problem, what
the failed system call and arguments were, and (VERY IMPORTANT)
should contain the standard system error message for what went wrong.
Here's a simple but sufficient example:
Be consistent.
Be nice.
168
Perl
The forward slashes in each case act as delimiters for the regular expression
(regex) that you are specifying. If you are comfortable with any other delimiter,
then you can use in place of forward slash.
$bar = "foo";
if ($bar =~ /foo/){
print "Second time is matching\n";
}else{
169
Perl
$bar = "foo";
if ($bar =~ m{foo}){
print "Second time is matching\n";
}else{
print "Second time is not matching\n";
}
You can omit m from m// if the delimiters are forward slashes, but for all other
delimiters you must use the m prefix.
Note that the entire match expression, that is the expression on the left of =~ or
!~ and the match operator, returns true (in a scalar context) if the expression
matches. Therefore the statement:
$true = ($foo =~ m/foo/);
will set $true to 1 if $foo matches the regex, or 0 if the match fails. In a list
context, the match returns the contents of any grouped expressions. For
170
Perl
example, when extracting the hours, minutes, and seconds from a time string,
we can use:
my ($hours, $minutes, $seconds) = ($time =~ m/(\d+):(\d+):(\d+)/);
Description
cg
Perl
foreach (@list)
{
$first = $1 if ?(foo.*)?;
$last = $1 if /(foo.*)/;
}
print "First: $first, Last: $last\n";
When above program is executed, it produces the following result:
First: food, Last: footbrdige
Perl
The PATTERN is the regular expression for the text that we are looking for. The
REPLACEMENT is a specification for the text or regular expression that we want
to use to replace the found text with. For example, we can replace all
occurrences of dog with cat using the following regular expression:
#/user/bin/perl
print "$string\n";
When above program is executed, it produces the following result:
The dog sat on the mat
Description
of
the
found
expression
with
the
173
Perl
print "$string\n";
When above program is executed, it produces the following result:
The cot sot on the mot.
Standard Perl ranges can also be used, allowing you to specify ranges of
characters either by letter or numerical value. To change the case of the string,
you might use the following syntax in place of the uc function.
$string =~ tr/a-z/A-Z/;
Description
Complements SEARCHLIST.
174
Perl
The /d modifier deletes the characters matching SEARCHLIST that do not have a
corresponding entry in REPLACEMENTLIST. For example:
#!/usr/bin/perl
print "$string\n";
When above program is executed, it produces the following result:
b b
b.
The last modifier, /s, removes the duplicate sequences of characters that were
replaced, so:
#!/usr/bin/perl
$string = 'food';
$string = 'food';
$string =~ tr/a-z/a-z/s;
print "$string\n";
When above program is executed, it produces the following result:
fod
Description
Matches beginning of line.
175
Perl
[...]
[^...]
{ n}
{ n,}
{ n, m}
a| b
Matches either a or b.
\w
\W
\s
\S
Matches nonwhitespace.
\d
\D
Matches nondigits.
176
Perl
\A
\Z
\z
\G
\b
\B
\1...\9
\10
[aeiou]
[^aeiou]
The ^ metacharacter matches the beginning of the string and the $ metasymbol
matches the end of the string. Here are some brief examples.
# nothing in the string (start and end are adjacent)
/^$/
Perl
/(a.)+/
Matching Boundaries
The \b matches at any word boundary, as defined by the difference between the
\w class and the \W class. Because \w includes the characters for a word, and
\W the opposite, this normally means the termination of a word.
The \B assertion matches any position that is not a word boundary. For
example:
/\bcat\b/ # Matches 'the cat sat' but not 'cat on the mat'
/\Bcat\B/ # Matches 'verification' but not 'the cat on the mat'
/\bcat\B/ # Matches 'catatonic' but not 'polecat'
/\Bcat\b/ # Matches 'polecat' but not 'catatonic'
178
Perl
Selecting Alternatives
The | character is just like the standard or bitwise OR within Perl. It specifies
alternate matches within a regular expression or group. For example, to match
"cat" or "dog" in an expression, you might use this:
if ($string =~ /cat|dog/)
You can group individual elements of an expression together in order to support
complex matches. Searching for two peoples names could be achieved with two
separate tests, like this:
if (($string =~ /Martin Brown/) ||
Grouping Matching
From a regular-expression point of view, there is no difference between except,
perhaps, that the former is slightly clearer.
$string =~ /(\S+)\s+(\S+)/;
and
$string =~ /\S+\s+\S+/;
However, the benefit of grouping is that it allows us to extract a sequence from
a regular expression. Groupings are returned as a list in the order in which they
appear in the original. For example, in the following fragment we have pulled out
the hours, minutes, and seconds from a string.
my ($hours, $minutes, $seconds) = ($time =~ m/(\d+):(\d+):(\d+)/);
As well as this direct method, matched groups are also available within the
special $x variables, where x is the number of the group within the regular
expression. We could therefore rewrite the preceding example as follows:
#!/usr/bin/perl
179
Perl
$time = "12:05:30";
$time =~ m/(\d+):(\d+):(\d+)/;
my ($hours, $minutes, $seconds) = ($1, $2, $3);
$date = '03/26/1999';
$date =~ s#(\d+)/(\d+)/(\d+)#$3/$1/$2#;
print "$date\n";
When above program is executed, it produces the following result:
1999/03/26
The \G Assertion
The \G assertion allows you to continue searching from the point where the last
match occurred. For example, in the following code, we have used \G so that we
can search to the correct position and then extract some information, without
having to create a more complex, single regular expression:
#!/usr/bin/perl
$string =~ /:\s+/g;
($time) = ($string =~ /\G(\d+:\d+:\d+)/);
$string =~ /.+\s+/g;
180
Perl
Regular-expression Examples
Literal Characters
Example
Perl
Description
Match "Perl".
Character Classes
Example
Description
[Pp]ython
rub[ye]
[aeiou]
[0-9]
[a-z]
[A-Z]
[a-zA-Z0-9]
181
Perl
[^aeiou]
[^0-9]
Description
\d
\D
\s
\S
\w
\W
Repetition Cases
Example
Description
ruby?
ruby*
ruby+
\d{3}
\d{3,}
182
Perl
\d{3,5}
Matches 3, 4, or 5 digits
Nongreedy Repetition
This matches the smallest number of repetitions:
Example
Description
<.*>
<.*?>
Description
\D\d+
No group: + repeats \d
(\D\d)+
([Pp]ython(, )?)+
Backreferences
This matches a previously matched group again:
Example
Description
([Pp])ython&\1ails
(['"])[^\1]*\1
Alternatives
Example
Description
183
Perl
python|perl
rub(y|le))
Python(!+|\?)
Anchors
This need to specify match positions.
Example
Description
^Python
Python$
\APython
Python\Z
\bPython\b
\brub\B
Python(?=!)
Python(?!!)
Description
R(?#comment)
R(?i)uby
184
Perl
R(?i:uby)
Same as above
rub(?:y|le))
185
Perl
$to = '[email protected]';
$from = '[email protected]';
$subject = 'Test Email';
$message = 'This is test email sent by Perl Script';
# Email Header
print MAIL "To: $to\n";
print MAIL "From: $from\n";
print MAIL "Subject: $subject\n\n";
# Email Body
print MAIL $message;
close(MAIL);
print "Email Sent Successfully\n";
Actually, the above script is a client email script, which will draft email and
submit to the server running locally on your Linux/Unix machine. This script will
not be responsible for sending email to actual destination. So you have to make
sure email server is properly configured and running on your machine to send
email to the given email ID.
186
Perl
$to = '[email protected]';
$from = '[email protected]';
$subject = 'Test Email';
$message = '<h1>This is test email sent by Perl Script</h1>';
# Email Header
print MAIL "To: $to\n";
print MAIL "From: $from\n";
print MAIL "Subject: $subject\n\n";
print MAIL "Content-type: text/html\n";
# Email Body
print MAIL $message;
close(MAIL);
print "Email Sent Successfully\n";
Perl
$make install
That's it and you will have MIME::Lite module installed on your machine. Now
you are ready to send your email with simple scripts explained below.
$to = '[email protected]';
$cc = '[email protected]';
$from = '[email protected]';
$subject = 'Test Email';
$message = 'This is test email sent by Perl Script';
$msg = MIME::Lite->new(
From
=> $from,
To
=> $to,
Cc
=> $cc,
Subject
=> $subject,
Data
=> $message
);
$msg->send;
print "Email Sent Successfully\n";
Perl
$to = '[email protected]';
$cc = '[email protected]';
$from = '[email protected]';
$subject = 'Test Email';
$message = '<h1>This is test email sent by Perl Script</h1>';
$msg = MIME::Lite->new(
From
=> $from,
To
=> $to,
Cc
=> $cc,
Subject
=> $subject,
Data
=> $message
);
Sending an Attachment
If you want to send an attachment, then following script serves the purpose:
#!/usr/bin/perl
use MIME::Lite;
$to = '[email protected]';
$cc = '[email protected]';
$from = '[email protected]';
$subject = 'Test Email';
$message = 'This is test email sent by Perl Script';
$msg = MIME::Lite->new(
From
=> $from,
To
=> $to,
189
Perl
Cc
=> $cc,
Subject
=> $subject,
Type
=> 'multipart/mixed'
);
=> 'text',
=> $message
);
=> 'image/gif',
Path
=> '/tmp/logo.gif',
Filename
=> 'logo.gif',
190
Perl
191
Perl
To Create a Server
To Create a Client
Following diagram shows the complete sequence of the calls used by Client and
Server to communicate with each other:
192
Perl
So socket function call issued by the server will be something like this:
use Socket
socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2]);
193
Perl
As the bind() is used by a server, which does not need to know its own address
so the argument list looks like this:
use Socket
$port = 12345;
$server_ip_address = "10.12.12.168";
bind( SOCKET, pack_sockaddr_in($port, inet_aton($server_ip_address)))
or die "Can't bind to port $port! \n";
The or die clause is very important because if a server dies without outstanding
connections, the port won't be immediately reusable unless you use the option
SO_REUSEADDR
using setsockopt() function.
Here pack_sockaddr_in() function is being used to pack the Port and IP
address into binary format.
194
Perl
$server_ip_address = "10.12.12.168";
connect( SOCKET, pack_sockaddr_in($port, inet_aton($server_ip_address)))
195
Perl
use strict;
use Socket;
196
Perl
# accepting a connection
my $client_addr;
while ($client_addr = accept(NEW_SOCKET, SOCKET)) {
# send them a message, close connection
my $name = gethostbyaddr($client_addr, AF_INET );
print NEW_SOCKET "Smile from the server";
print "Connection recieved from $name\n";
close NEW_SOCKET;
}
To run the server in background mode issue the following command on Unix
prompt:
$perl sever.pl&
use strict;
use Socket;
Perl
my $line;
while ($line = <SOCKET>) {
print "$line\n";
}
close SOCKET or die "close: $!";
Now let's start our client at the command prompt, which will connect to the
server and read message sent by the server and displays the same on the
screen as follows:
$perl client.pl
Smile from the server
NOTE: If you are giving the actual IP address in dot notation, then it is
recommended to provide IP address in the same format in both client as well as
server to avoid any confusion.
198
Perl
We have already studied references in Perl and Perl anonymous arrays and
hashes. Object Oriented concept in Perl is very much based on references and
anonymous array and hashes. Let's start learning basic concepts of Object
Oriented Perl.
Object Basics
There are three main terms, explained from the point of view of how Perl
handles objects. The terms are object, class, and method.
A method within Perl is a subroutine, defined with the package. The first
argument to the method is an object reference or a package name,
depending on whether the method affects the current object or the class.
Defining a Class
It is very simple to define a class in Perl. A class is corresponding to a Perl
Package in its simplest form. To create a class in Perl, we first build a package.
A package is a self-contained unit of user-defined variables and subroutines,
which can be re-used over and over again.
Perl Packages provide a separate namespace within a Perl program which keeps
subroutines and variables independent from conflicting with those in other
packages.
To declare a class named Person in Perl we do:
package Person;
The scope of the package definition extends to the end of the file, or until
another package keyword is encountered.
199
Perl
=> shift,
_ssn
=> shift,
};
# Print all the values just for clarification.
print "First Name is $self->{_firstName}\n";
print "Last Name is $self->{_lastName}\n";
print "SSN is $self->{_ssn}\n";
bless $self, $class;
return $self;
}
Now Let us see how to create an Object.
$object = new Person( "Mohammad", "Saleem", 23234345);
You can use simple hash in your consturctor if you don't want to assign any
value to any class variable. For example:
package Person;
sub new
{
200
Perl
my $class = shift;
my $self = {};
bless $self, $class;
return $self;
}
Defining Methods
Other object-oriented languages have the concept of security of data to prevent
a programmer from changing an object data directly and they provide accessor
methods to modify object data. Perl does not have private variables but we can
still use the concept of helper methods to manipulate object data.
Lets define a helper method to get persons first name:
sub getFirstName {
return $self->{_firstName};
}
Another helper function to set persons first name:
sub setFirstName {
my ( $self, $firstName ) = @_;
$self->{_firstName} = $firstName if defined($firstName);
return $self->{_firstName};
}
Now lets have a look into complete example: Keep Person package and helper
functions into Person.pm file.
#!/usr/bin/perl
package Person;
sub new
{
my $class = shift;
my $self = {
_firstName => shift,
201
Perl
_lastName
=> shift,
_ssn
=> shift,
};
# Print all the values just for clarification.
print "First Name is $self->{_firstName}\n";
print "Last Name is $self->{_lastName}\n";
print "SSN is $self->{_ssn}\n";
bless $self, $class;
return $self;
}
sub setFirstName {
my ( $self, $firstName ) = @_;
$self->{_firstName} = $firstName if defined($firstName);
return $self->{_firstName};
}
sub getFirstName {
my( $self ) = @_;
return $self->{_firstName};
}
1;
Now let's make use of Person object in employee.pl file as follows:
#!/usr/bin/perl
use Person;
Perl
$object->setFirstName( "Mohd." );
Inheritance
Object-oriented programming has very good and useful concept called
inheritance. Inheritance simply means that properties and methods of a parent
class will be available to the child classes. So you don't have to write the same
code again and again, you can just inherit a parent class.
For example, we can have a class Employee, which inherits from Person. This is
referred to as an "isa" relationship because an employee is a person. Perl has a
special variable, @ISA, to help with this. @ISA governs (method) inheritance.
Following are the important points to be considered while using inheritance:
Perl searches the class of the specified object for the given method or
attribute, i.e., variable.
Perl searches the classes defined in the object class's @ISA array.
If a matching method still cannot be found, then Perl searches for the
method within the UNIVERSAL class (package) that comes as part of the
standard Perl library.
If the method still has not found, then Perl gives up and raises a runtime
exception.
So to create a new Employee class that will inherit methods and attributes from
our Person class, we simply code as follows: Keep this code into Employee.pm.
#!/usr/bin/perl
203
Perl
package Employee;
use Person;
use strict;
our @ISA = qw(Person);
Now Employee Class has all the methods and attributes inherited from Person
class and you can use them as follows: Use main.pl file to test it:
#!/usr/bin/perl
use Employee;
204
Perl
Method Overriding
The child class Employee inherits all the methods from the parent class Person.
But if you would like to override those methods in your child class then you can
do it by giving your own implementation. You can add your additional functions
in child class or you can add or modify the functionality of an existing methods
in its parent class. It can be done as follows: modify Employee.pm file.
#!/usr/bin/perl
package Employee;
use Person;
use strict;
our @ISA = qw(Person);
# Override constructor
sub new {
my ($class) = @_;
= undef;
$self->{_title} = undef;
bless $self, $class;
return $self;
}
Perl
sub getLastName {
my( $self ) = @_;
return $self->{_lastName};
}
1;
Now let's again try to use Employee object in our main.pl file and execute it.
#!/usr/bin/perl
use Employee;
Perl
Default Autoloading
Perl offers a feature which you would not find in any other programming
languages: a default subroutine. Which means, if you define a function
called AUTOLOAD(), then any calls to undefined subroutines will call
AUTOLOAD() function automatically. The name of the missing subroutine is
accessible within this subroutine as $AUTOLOAD.
Default autoloading functionality is very useful for error handling. Here is an
example to implement AUTOLOAD, you can implement this function in your own
way.
sub AUTOLOAD
{
my $self = shift;
my $type = ref ($self) || croak "$self is not an object";
my $field = $AUTOLOAD;
$field =~ s/.*://;
unless (exists $self->{$field})
{
croak "$field does not exist in object/class $type";
}
if (@_)
{
return $self->($name) = shift;
}
else
{
return $self->($name);
}
207
Perl
For Example, you can simply put the following method DESTROY in your class:
package MyClass;
...
sub DESTROY
{
print "MyClass::DESTROY called\n";
}
Perl
sub new
{
print "MyClass::new called\n";
my $type = shift;
my $self = {};
sub DESTROY
{
print "MyClass::DESTROY called\n";
}
sub MyMethod
{
print "MyClass::MyMethod called!\n";
}
sub new
{
print "MySubClass::new called\n";
my $type = shift;
my $self = MyClass->new;
209
Perl
sub DESTROY
{
print "MySubClass::DESTROY called\n";
}
sub MyMethod
{
my $self = shift;
$self->SUPER::MyMethod();
print "
MySubClass::MyMethod called!\n";
$myObject = MyClass->new();
$myObject->MyMethod();
$myObject2 = MySubClass->new();
$myObject2->MyMethod();
Perl
undef $myObject3;
211
Perl
This chapter teaches you how to access a database inside your Perl script.
Starting from Perl 5 has become very easy to write database applications
using DBI module. DBI stands for Database Independent Interface for Perl,
which means DBI provides an abstraction layer between the Perl code and the
underlying database, allowing you to switch database implementations really
easily.
The DBI is a database access module for the Perl programming language. It
provides a set of methods, variables, and conventions that provide a consistent
database interface, independent of the actual database being used.
Here DBI is responsible of taking all SQL commands through the API, (i.e.,
Application Programming Interface) and to dispatch them to the appropriate
driver for actual execution. And finally, DBI is responsible of taking results from
the driver and giving back it to the calling scritp.
$dbh
$sth
$h
Perl
$rc
$rv
@ary
$rows
$fh
A filehandle
undef
\%attr
Database Connection
Assuming we are going to work with MySQL database. Before connecting to a
database make sure of the followings. You can take help of our MySQL tutorial in
case you are not aware about how to create database and tables in MySQL
database.
use DBI
use strict;
my $driver = "mysql";
my $database = "TESTDB";
my $dsn = "DBI:$driver:database=$database";
my $userid = "testuser";
my $password = "test123";
213
Perl
INSERT Operation
INSERT operation is required when you want to create some records into a table.
Here we are using table TEST_TABLE to create our records. So once our
database connection is established, we are ready to create records into
TEST_TABLE. Following is the procedure to create single record into
TEST_TABLE. You can create as many as records you like using the same
concept.
Record creation takes the following steps:
Executing SQL query to select all the results from the database. This will
be done using execute() API.
Perl
my $first_name = "john";
my $last_name = "poul";
my $sex = "M";
my $income = 13000;
my $age = 30;
my $sth = $dbh->prepare("INSERT INTO TEST_TABLE
(FIRST_NAME, LAST_NAME, SEX, AGE, INCOME )
values
(?,?,?,?)");
$sth->execute($first_name,$last_name,$sex, $age, $income)
or die $DBI::errstr;
$sth->finish();
$dbh->commit or die $DBI::errstr;
READ Operation
READ Operation on any databasse means to fetch some useful information from
the database, i.e., one or more records from one or more tables. So once our
database connection is established, we are ready to make a query into this
database. Following is the procedure to query all the records having AGE greater
than 20. This will take four steps:
Executing SQL query to select all the results from the database. This will
be done using execute() API.
Fetching all the results one by one and printing those results.This will be
done using fetchrow_array() API.
Perl
UPDATE Operation
UPDATE Operation on any database means to update one or more records
already available in the database tables. Following is the procedure to update all
the records having SEX as 'M'. Here we will increase AGE of all the males by one
year. This will take three steps:
Prearing SQL query based on required conditions. This will be done using
prepare() API.
Executing SQL query to select all the results from the database. This will
be done using execute() API.
Perl
AGE = AGE + 1
AGE = AGE + 1
INCOME = ?
217
Perl
DELETE Operation
DELETE operation is required when you want to delete some records from your
database. Following is the procedure to delete all the records from TEST_TABLE
where AGE is equal to 30. This operation will take the following steps.
Prearing SQL query based on required conditions. This will be done using
prepare() API.
Executing SQL query to delete required records from the database. This
will be done using execute() API.
operation
otherwise
you
$age = 30;
my $sth = $dbh->prepare("DELETE FROM TEST_TABLE
WHERE AGE = ?");
$sth->execute( $age ) or die $DBI::errstr;
print "Number of rows deleted :" + $sth->rows;
$sth->finish();
$dbh->commit or die $DBI::errstr;
Using do Statement
If you're doing an UPDATE, INSERT, or DELETE there is no data that comes back
from the database, so there is a short cut to perform this operation. You can
use do statement to execute any of the command as follows.
$dbh->do('DELETE FROM TEST_TABLE WHERE age =30');
do returns a true value if it succeeded, and a false value if it failed. Actually, if it
succeeds it returns the number of affected rows. In the example it would return
the number of rows that were actually deleted.
COMMIT Operation
Commit is the operation which gives a green signal to database to finalize the
changes and after this operation no change can be reverted to its orignal
position.
Here is a simple example to call commit API.
218
Perl
ROLLBACK Operation
If you are not satisfied with all the changes or you encounter an error in
between of any operation , you can revert those changes to use rollback API.
Here is a simple example to call rollback API.
$dbh->rollback or die $dbh->errstr;
Begin Transaction
Many databases support transactions. This means that you can make a whole
bunch of queries which would modify the databases, but none of the changes
are actually made. Then at the end, you issue the special SQL query COMMIT,
and all the changes are made simultaneously. Alternatively, you can issue the
query ROLLBACK, in which case all the changes are thrown away and database
remains unchanged.
Perl DBI module provided begin_work API, which enables transactions (by
turning AutoCommit off) until the next call to commit or rollback. After the next
commit or rollback, AutoCommit will automatically be turned on again.
$rc
= $dbh->begin_work
or die $dbh->errstr;
AutoCommit Option
If your transactions are simple, you can save yourself the trouble of having to
issue a lot of commits. When you make the connect call, you can specify
an AutoCommit option which will perform an automatic commit operation after
every successful query. Here's what it looks like:
my $dbh = DBI->connect($dsn, $userid, $password,
{AutoCommit => 1})
or die $DBI::errstr;
Here AutoCommit can take value 1 or 0, where 1 means AutoCommit is on and 0
means AutoCommit is off.
Perl
program instead of returning a failure code. If all you want is to abort the
program on an error, this can be convenient. Here's what it looks like:
my $dbh = DBI->connect($dsn, $userid, $password,
{RaiseError => 1})
or die $DBI::errstr;
Here RaiseError can take value 1 or 0.
Disconnecting Database
To disconnect Database connection, use disconnect API as follows:
$rc = $dbh->disconnect
or warn $dbh->errstr;
The transaction behaviour of the disconnect method is, sadly, undefined. Some
database systems (such as Oracle and Ingres) will automatically commit any
outstanding changes, but others (such as Informix) will rollback any outstanding
changes. Applications not using AutoCommit should explicitly call commit or
rollback before calling disconnect.
Perl
prepare the appropriate statement as needed, and substitute the placeholder for
non-NULL cases:
$sql_clause = defined $age? "age = ?" : "age IS NULL";
$sth = $dbh->prepare(qq{
SELECT FIRST_NAME FROM TEST_TABLE WHERE $sql_clause
});
$sth->execute(defined $age ? $age : ());
installed_drivers
%drivers = DBI->installed_drivers();
Returns a list of driver name and driver handle pairs for all drivers 'installed'
(loaded) into the current process. The driver name does not include the 'DBD::'
prefix.
data_sources
@ary = DBI->data_sources($driver);
Returns a list of data sources (databases) available via the named driver. If
$driver is empty or undef, then the value of the DBI_DRIVER environment
variable is used.
quote
$sql = $dbh->quote($value);
$sql = $dbh->quote($value, $data_type);
221
Perl
Quote a string literal for use as a literal value in an SQL statement, by escaping
any special characters (such as quotation marks) contained within the string and
adding the required type of outer quotation marks.
$sql = sprintf "SELECT foo FROM bar WHERE baz = %s",
$dbh->quote("Don't");
For most database types, quote would return 'Don''t' (including the outer
quotation marks). It is valid for the quote() method to return an SQL expression
that evaluates to the desired string. For example:
$quoted = $dbh->quote("one\ntwo\0three")
errstr
$str = $h->errstr;
or
$str = $DBI::errstr
or
$str = $h->errstr
222
Perl
Returns the native database engine error message from the last DBI method
called. This has the same lifespan issues as the "err" method described above.
This is equivalent to $DBI::errstr or $h->errstr.
rows
$rv = $h->rows;
or
$rv = $DBI::rows
This returns the number of rows effected by previous SQL statement and
equivalent to $DBI::rows.
trace
$h->trace($trace_settings);
DBI sports an extremely useful ability to generate runtime tracing information of
what it's doing, which can be a huge time-saver when trying to track down
strange problems in your DBI programs. You can use different values to set
trace level. These values varies from 0 to 4. The value 0 means disable trace
and 4 means generate complete trace.
223
Perl
224
Perl
What is CGI ?
The CGI specs are currently maintained by the NCSA and NCSA defines
CGI is as follows:
Web Browsing
To understand the concept of CGI, lets see what happens when we click a hyper
link available on a web page to browse a particular web page or URL.
Your browser contacts web server using HTTP protocol and demands for
the URL, i.e., web page filename.
Web Server will check the URL and will look for the filename requested. If
web server finds that file then it sends the file back to the browser without
any further execution otherwise sends an error message indicating that
you have requested a wrong file.
Web browser takes response from web server and displays either the
received file content or an error message in case file is not found.
225
Perl
226
Perl
print "Content-type:text/html\r\n\r\n";
print '<html>';
print '<head>';
print '<title>Hello Word - First CGI Program</title>';
print '</head>';
print '<body>';
print '<h2>Hello Word! This is my first CGI program</h2>';
print '</body>';
print '</html>';
1;
Now if you click hello.cgi link then request goes to web server who search for
hello.cgi in /cgi-bin directory, execute it and whatever result got generated, web
server sends that result back to the web browser, which is as follows:
Perl
Header
Description
Content-type: String
Last-modified: String
Content-length: String
Set-Cookie: String
Description
CONTENT_TYPE
CONTENT_LENGTH
HTTP_COOKIE
Perl
pair.
HTTP_USER_AGENT
The
User-Agent
request-header
field
contains
information about the user agent originating the
request. Its name of the web browser.
PATH_INFO
QUERY_STRING
REMOTE_ADDR
REMOTE_HOST
REQUEST_METHOD
SCRIPT_FILENAME
SCRIPT_NAME
SERVER_NAME
SERVER_SOFTWARE
Here is a small CGI program to list down all the CGI variables supported by your
Web server.
#!/usr/bin/perl
Perl
{
print "<b>$_</b>: $ENV{$_}<br>\n";
}
1;
# HTTP Header
print "Content-Type:application/octet-stream; name=\"FileName\"\r\n";
print "Content-Disposition: attachment; filename=\"FileName\"\r\n\n";
230
Perl
Perl
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$first_name = $FORM{first_name};
$last_name
= $FORM{last_name};
print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Hello - Second CGI Program</title>";
print "</head>";
print "<body>";
print "<h2>Hello $first_name $last_name - Second CGI Program</h2>";
print "</body>";
print "</html>";
1;
<br>
Perl
First Name:
Submit
Last Name:
= $FORM{last_name};
233
Perl
print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Hello - Second CGI Program</title>";
print "</head>";
print "<body>";
print "<h2>Hello $first_name $last_name - Second CGI Program</h2>";
print "</body>";
print "</html>";
1;
Let us take again same examle as above, which passes two values using HTML
FORM and submit button. We are going to use CGI script hello_post.cgi to
handle this input.
<FORM action="/cgi-bin/hello_post.cgi" method="POST">
First Name: <input type="text" name="first_name">
<br>
Submit
Perl
Physics
Submit
Below is checkbox.cgi script to handle input given by web browser for radio
button.
#!/usr/bin/perl
Perl
}
if( $FORM{physics} ){
$physics_flag ="ON";
}else{
$physics_flag ="OFF";
}
print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Checkbox - Third CGI Program</title>";
print "</head>";
print "<body>";
print "<h2> CheckBox Maths is : $maths_flag</h2>";
print "<h2> CheckBox Physics is : $physics_flag</h2>";
print "</body>";
print "</html>";
1;
Physics
Submit
Below is radiobutton.cgi script to handle input given by the web browser for
radio button.
236
Perl
#!/usr/bin/perl
print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Radio - Fourth CGI Program</title>";
print "</head>";
print "<body>";
print "<h2> Selected Subject is $subject</h2>";
print "</body>";
print "</html>";
1;
237
Perl
Submit
Below is the textarea.cgi script to handle input given by the web browser.
#!/usr/bin/perl
Perl
$FORM{$name} = $value;
}
$text_content = $FORM{textcontent};
print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Text Area - Fifth CGI Program</title>";
print "</head>";
print "<body>";
print "<h2> Entered Text Content is $text_content</h2>";
print "</body>";
print "</html>";
1;
Perl
print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Dropdown Box - Sixth CGI Program</title>";
print "</head>";
print "<body>";
print "<h2> Selected Subject is $subject</h2>";
print "</body>";
print "</html>";
1;
240
Perl
How It Works
Your server sends some data to the visitor's browser in
browser may accept the cookie. If it does, it is stored
the visitor's hard drive. Now, when the visitor arrives
site, the cookie is available for retrieval. Once
knows/remembers what was stored.
Expires: The date the cookie will expire. If this is blank, the cookie will
expire when the visitor quits the browser.
Path: The path to the directory or web page that set the cookie. This may
be blank if you want to retrieve the cookie from any directory or page.
Secure: If this field contains the word "secure" then the cookie may only
be retrieved with a secure server. If this field is blank, no such restriction
exists.
Name=Value: Cookies are set and retrviewed in the form of key and
value pairs.
Setting up Cookies
It is very easy to send cookies to browser. These cookies will be sent along with
the HTTP Header. Assuming you want to set UserID and Password as cookies. So
it will be done as follows:
#!/usr/bin/perl
print "Set-Cookie:UserID=XYZ;\n";
print "Set-Cookie:Password=XYZ123;\n";
print "Set-Cookie:Expires=Tuesday, 31-Dec-2007 23:12:40 GMT";\n";
241
Perl
print "Set-Cookie:Domain=www.tutorialspoint.com;\n";
print "Set-Cookie:Path=/perl;\n";
print "Content-type:text/html\r\n\r\n";
...........Rest of the HTML Content goes here....
Here we used Set-Cookie HTTP header to set cookies. It is optional to set
cookies attributes like Expires, Domain, and Path. It is important to note that
cookies are set before sending magic line "Content-type:text/html\r\n\r\n.
Retrieving Cookies
It is very easy to retrieve all the set cookies. Cookies are stored in CGI
environment variable HTTP_COOKIE and they will have following form.
key1=value1;key2=value2;key3=value3....
Here is an example of how to retrieve cookies.
#!/usr/bin/perl
$rcvd_cookies = $ENV{'HTTP_COOKIE'};
@cookies = split /;/, $rcvd_cookies;
foreach $cookie ( @cookies ){
($key, $val) = split(/=/, $cookie); # splits on the first =.
$key =~ s/^\s+//;
$val =~ s/^\s+//;
$key =~ s/\s+$//;
$val =~ s/\s+$//;
if( $key eq "UserID" ){
$user_id = $val;
}elsif($key eq "Password"){
$password = $val;
}
}
print "User ID
= $user_id\n";
Perl
User ID = XYZ
Password = XYZ123
CGI Module
Berkeley cgi-lib.pl
243
Perl
You can explicitly refer to variables within a package using the :: package
qualifier.
Following is an example having main and Foo packages in a file. Here special
variable __PACKAGE__ has been used to print the package name.
#!/usr/bin/perl
package Foo;
# This is Foo package
$i = 10;
print "Package name : " , __PACKAGE__ , " $i\n";
package main;
# This is again main package
$i = 100;
244
Perl
" $Foo::i\n";
1;
When above code is executed, it produces the following result:
Package name : main 1
Package name : Foo 10
Package name : main 100
Package name : main 10
Every BEGIN block is executed after the perl script is loaded and compiled
but before any other statement is executed.
Every END block is executed just before the perl interpreter exits.
The BEGIN and END blocks are particularly useful when creating Perl
modules.
package Foo;
print "Begin and Block Demo\n";
BEGIN {
print "This is BEGIN Block\n"
}
245
Perl
END {
print "This is END Block\n"
}
1;
When above code is executed, it produces the following result:
This is BEGIN Block
Begin and Block Demo
This is END Block
package Foo;
sub bar {
print "Hello $_[0]\n"
}
sub blat {
print "World $_[0]\n"
}
1;
Few important points about Perl modules
Both use the list of search paths in @INC to find the module.
Both functions require and use call the eval function to process the code.
The 1; at the bottom causes eval to evaluate to TRUE (and thus not fail).
246
Perl
require Foo;
Foo::bar( "a" );
Foo::blat( "b" );
You must have noticed that the subroutine names must be fully qualified to call
them. It would be nice to enable the subroutine bar and blat to be imported into
our own namespace so we wouldn't have to use the Foo:: qualifier.
use Foo;
bar( "a" );
blat( "b" );
Notice that we didn't have to fully qualify the package's function names.
The use function will export a list of symbols from a module given a few added
statements inside a module.
require Exporter;
@ISA = qw(Exporter);
Then, provide a list of symbols (scalars, lists, hashes, subroutines, etc) by filling
the list variable named @EXPORT: For Example:
package Module;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(bar blat);
247
Perl
# Not exported!
1;
ModuleName
For example, if your module is available in Person.pm file, then simply issue the
following command:
$h2xs -AX -n Person
This will produce the following result:
Writing Person/lib/Person.pm
Writing Person/Makefile.PL
Writing Person/README
Writing Person/t/Person.t
Writing Person/Changes
Writing Person/MANIFEST
Here is the descritpion of these options:
-A omits the Autoloader code (best used by modules that define a large
number of infrequently used subroutines).
Changes
248
Perl
Makefile.PL
README
t/ (test files)
So finally, you tar this directory structure into a file Person.tar.gz and you can
ship it. You will have to update README file with the proper instructions. You can
also provide some test examples files in t directory.
249
Perl
You can use Perl in various ways to create new processes as per your
requirements. This tutorial will list down few important and most frequently used
methods of creating and managing Perl processes.
Every process created using any of the mentioned methods, maintains its
own virtual environment with-in %ENV variable.
The exit() function always exits just the child process which executes this
function and the main process as a whole will not exit unless all running
child-processes have exited.
Backstick Operator
This simplest way of executing any Unix command is by using backstick
operator. You simply put your command inside the backstick operator, which will
result in execution of the command and returns its result which can be stored as
follows:
#!/usr/bin/perl
1;
When the above code is executed, it lists down all the files and directories
available in the current directory:
drwxr-xr-x 3 root root 4096 Sep 14 06:46 9-14
drwxr-xr-x 4 root root 4096 Sep 13 07:54 android
250
Perl
544
6 16:49 MIME-Lite-3.01
1;
When above code is executed, it lists down all the files and directories available
in the current directory:
drwxr-xr-x 3 root root 4096 Sep 14 06:46 9-14
drwxr-xr-x 4 root root 4096 Sep 13 07:54 android
-rw-r--r-- 1 root root
drwxr-xr-x 3
544
6 16:49 MIME-Lite-3.01
system('echo $PATH');
system("echo $PATH");
251
Perl
1;
When above code is executed, it produces the following result depending on
what is set in shell variable $PATH.
/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin
I am Perl Variable
/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin
if(!defined($pid = fork())) {
# fork returned undef, so unsuccessful
die "Cannot fork a child: $!";
}elsif ($pid == 0) {
print "Printed by child process\n";
exec("date") || die "can't exec date: $!";
} else {
# fork returned 0 nor undef
# so this branch is parent
print "Printed by parent process\n";
$ret = waitpid($pid, 0);
print "Completed process id: $ret\n";
252
Perl
1;
When above code is executed, it produces the following result:
Printed by parent process
Printed by child process
Tue Sep 17 15:41:08 CDT 2013
Completed process id: 17777
The wait() and waitpid() can be passed as a pseudo-process ID returned by
fork(). These calls will properly wait for the termination of the pseudo-process
and return its status. If you fork without ever waiting on your children
using waitpid() function, you will accumulate zombies. On Unix systems, you
can avoid this by setting $SIG{CHLD} to "IGNORE" as follows:
#!/usr/bin/perl
if(!defined($pid = fork())) {
# fork returned undef, so unsuccessful
die "Cannot fork a child: $!";
}elsif ($pid == 0) {
print "Printed by child process\n";
exec("date") || die "can't exec date: $!";
} else {
# fork returned 0 nor undef
# so this branch is parent
print "Printed by parent process\n";
$ret = waitpid($pid, 0);
print "Completed process id: $ret\n";
}
253
Perl
1;
When above code is executed, it produces the following result:
Printed by parent process
Printed by child process
Tue Sep 17 15:44:07 CDT 2013
Completed process id: -1
1;
254
Perl
while(<DATA>){
print $_;
}
255
Perl
__END__
__END__
What is POD?
Pod is a simple-to-use markup language used for writing documentation for Perl,
Perl programs, and Perl modules. There are various translators available for
converting Pod to various formats like plain text, HTML, man pages, and more.
Pod markup consists of three basic kinds of paragraphs:
Perl
=pod
=head1 Heading Text
=head2 Heading Text
=head3 Heading Text
=head4 Heading Text
=over indentlevel
=item stuff
=back
=begin format
=end format
=for format text...
=encoding type
=cut
POD Examples
Consider the following POD:
=head1 SYNOPSIS
Copyright 2005 [TUTORIALSOPOINT].
=cut
You can use pod2html utility available on Linux to convert above POD into
HTML, so it will produce following result:
Perl
=over 4
=item * This is a bulleted list.
=item * Here's another item.
=back
=begin html
<p>
Here's some embedded HTML.
=end html
When you convert the above POD into HTML using pod2html, it will produce the
following result:
An Example List
This is a bulleted list.
Here's another item.
Here's some embedded HTML. In this block I can include images, apply
styles, or do anything else I can do with HTML. pod parsers that aren't
outputting HTML will completely ignore it.
258
Perl
abs
Description
This function returns the absolute value of its argument. If pure interger value is
passed then it will return it as it is, but if a string is passed then it will return
zero. If VALUE is omitted then it uses $_
Syntax
Following is the simple syntax for this function:
abs VALUE
abs
Return Value
This function returns the absolute value of its argument.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
$par1 = 10.25;
$par2 = 20;
$par3 = "ABC";
$abs1 = abs($par1);
$abs2 = abs($par2);
$abs3 = abs($par3);
Perl
accept
Description
This function accepts an incoming connection on the existing GENERICSOCKET,
which should have been created with socket and bound to a local address using
bind. The new socket, which will be used for communication with the client will
be NEWSOCKET. GENERICSOCKET will remain unchanged.
Syntax
Following is the simple syntax for this function:
accept NEWSOCKET,GENERICSOCKET
Return Value
This function returns 0 on failure and Packed address of remote host on success.
Example
Following is the example code showing script to create a server:
#!/usr/bin/perl
When above code is executed, it produces the following result:
alarm
Description
This function sets the "alarm," causing the current process to receive a SIGALRM
signal in EXPR seconds. If EXPR is omitted, the value of $_ is used instead.
260
Perl
The actual time delay is not precise, since different systems implement the
alarm functionality differently. The actual time may be up to a second more or
less than the requested value. You can only set one alarm timer at any one time.
If a timer is already running and you make a new call to the alarm function, the
alarm timer is reset to the new value. A running timer can be reset without
setting a new timer by specifying a value of 0.
Syntax
Following is the simple syntax for this function:
alarm EXPR
alarm
Return Value
This function returns Integer value ie. number of seconds remaining for previous
timer.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
eval {
local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
alarm $timeout;
$nread = sysread SOCKET, $buffer, $size;
alarm 0;
};
if ($@) {
die unless $@ eq "alarm\n";
# timed out
}
else {
# didn't
}
When above code is executed, it produces the following result:
261
Perl
atan2
Description
This function returns the arctangent of Y/X in the range -PI to PI.
Syntax
Following is the simple syntax for this function:
atan2 Y,X
Return Value
This function returns arctangent of Y/X in the range -PI to PI.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
$Y = 30;
$X = 60;
262
Perl
bind
Description
This function binds the network ADDRESS to the filehandle identified by
SOCKET. The ADDRESS should be a packed address of the appropriate type for
the socket being opened.
Syntax
Following is the simple syntax for this function:
bind SOCKET, ADDRESS
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
When above code is executed, it produces the following result:
binmode
Description
This function sets the format for FILEHANDLE to be read from and written to as
binary on the operating systems that differentiate between the two. Files that
are not in binary have CR LF sequences converted to LF on input, and LF to CR
LF on output. This is vital for operating systems that use two characters to
separate lines within text files (MS-DOS), but has no effect on operating systems
that use single characters (Unix, Mac OS, QNX).
Syntax
Following is the simple syntax for this function:
binmode FILEHANDLE
263
Perl
Return Value
This function returns undef on failure or invalid FILEHANDLE and 1 on success.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
When above code is executed, it produces the following result:
bless
Description
This function tells the entity referenced by REF that it is now an object in the
CLASSNAME package, or the current package if CLASSNAME is omitted. Use of
the two-argument form of bless is recommended.
Syntax
Following is the simple syntax for this function:
bless REF, CLASSNAME
bless REF
Return Value
This function returns the reference to an object blessed into CLASSNAME.
Example
Following is the example code showing its basic usage, the object reference is
created by blessing a reference to the package's class.:
#!/usr/bin/perl
package Person;
sub new
{
264
Perl
my $class = shift;
my $self = {
_firstName => shift,
_lastName
=> shift,
_ssn
=> shift,
};
# Print all the values just for clarification.
print "First Name is $self->{_firstName}\n";
print "Last Name is $self->{_lastName}\n";
print "SSN is $self->{_ssn}\n";
bless $self, $class;
return $self;
}
When above code is executed, it produces the following result:
caller
Description
This function returns information about the current subroutines caller. In a scalar
context, returns the caller's package name or the package name of the caller
EXPR steps up.
In a list context, with no arguments specified, caller returns the package name,
file name and line within the file for the caller of the current subroutine.
If EXPR is specified, caller returns extended information for the caller EXPR steps
up. That is, when called with an argument of 1, it returns the information for the
caller (parent) of the current subroutine, with 2 the caller of the caller
(grandparent) of the current subroutine, and so on.
Syntax
Following is the simple syntax for this function:
caller EXPR
265
Perl
caller
Return Value
This function returns undef on failure, basic information when called with no
arguments and extended information when called with an argument.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
When above code is executed, it produces the following result:
chdir
Description
This function changes the current working directory to EXPR, or to the user's
home directory if none is specified. This function call is equivalent to Unix
command cd EXPR.
Syntax
Following is the simple syntax for this function:
chdir EXPR
chdir
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage, assume you are working
in /user/home/tutorialspoint directory.:
#!/usr/bin/perl
chdir "/usr/home";
266
Perl
chmod
Description
This function changes the mode of the files specified in LIST to the MODE
specified. The value of MODE should be in octal. You must check the return
value against the number of files that you attempted to change to determine
whether the operation failed. This funcation call is equivalent to Unix Command
chmod MODE FILELIST.
Syntax
Following is the simple syntax for this function:
chmod MODE, LIST
Return Value
This function returns Integer, number of files successfully changed.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
# this is best
267
Perl
chomp
Description
This safer version of chop removes any trailing string that corresponds to the
current value of $/ (also known as $INPUT_RECORD_SEPARATOR in the English
module). It returns the total number of characters removed from all its
arguments. By default $/ is set to new line character.
Syntax
Following is the simple syntax for this function:
chomp VARIABLE
chomp( LIST )
chomp
Return Value
This function returns Integer, number of bytes removed for all strings.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
= chomp( $string1 );
= chomp( $string1 );
268
Perl
chop
Description
This function removes the last character from EXPR, each element of LIST, or $_
if no value is specified.
Syntax
Following is the simple syntax for this function:
chop VARIABLE
chop( LIST )
chop
Return Value
This function returns the character removed from EXPR and in list context, the
character is removed from the last element of LIST.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
= chop( $string1 );
269
Perl
chown
Description
This function changes the owner (and group) of a list of files. The first two
elements of the list must be the numeric uid and gid, in that order. This
funcation call works in similar way as unix command chown. Thus you should
have sufficient privilege to change the permission of the file.
Syntax
Following is the simple syntax for this function:
chown USERID, GROUPID, LIST
Return Value
This function returns the number of files successfully changed.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
270
Perl
chr
Description
This function returns the character represented by the numeric value of EXPR, or
$_ if omitted, according to the current character set. Note that the character
number will use the Unicode character numbers for numerical values above 127.
Syntax
Following is the simple syntax for this function:
chr EXPR
chr
Return Value
This function returns the Character corresponding to the numeric value of EXPR.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
271
Perl
BIN
Symbol
HTML
Code
Description
000
00
00000000 NUL
�
Null char
001
01
00000001 SOH

Start of Heading
002
02
00000010 STX

Start of Text
003
03
00000011 ETX

End of Text
004
04
00000100 EOT

End of Transmission
005
05
00000101 ENQ

Enquiry
006
06
00000110 ACK

Acknowledgment
007
07
00000111 BEL

Bell
010
08
00001000 BS

Back Space
011
09
00001001 HT
	
Horizontal Tab
10
012
0A
00001010 LF


Line Feed
11
013
0B
00001011 VT

Vertical Tab
12
014
0C
00001100 FF

Form Feed
13
015
0D
00001101 CR

Carriage Return
14
016
0E
00001110 SO

272
Perl
15
017
0F
00001111 SI

Shift In / X-Off
16
020
10
00010000 DLE

17
021
11
00010001 DC1

18
022
12
00010010 DC2

Device Control 2
19
023
13
00010011 DC3

Device
XOFF)
20
024
14
00010100 DC4

Device Control 4
21
025
15
00010101 NAK

Negative Acknowledgement
22
026
16
00010110 SYN

Synchronous Idle
23
027
17
00010111 ETB

24
030
18
00011000 CAN

Cancel
25
031
19
00011001 EM

End of Medium
26
032
1A
00011010 SUB

Substitute
27
033
1B
00011011 ESC

Escape
28
034
1C
00011100 FS

File Separator
29
035
1D
00011101 GS

Group Separator
30
036
1E
00011110 RS

Record Separator
31
037
1F
00011111 US

Unit Separator
32
040
20
00100000
 
Space
33
041
21
00100001 !
!
Exclamation mark
34
042
22
00100010 "
"
Double quotes
35
043
23
00100011 #
#
Number
Control
(oft.
273
Perl
36
044
24
00100100 $
$
Dollar
37
045
25
00100101 %
%
Procenttecken
38
046
26
00100110 &
&
Ampersand
39
047
27
00100111 '
'
Single quote
40
050
28
00101000 (
(
Open parenthesis
41
051
29
00101001 )
)
Close parenthesis
42
052
2A
00101010 *
*
Asterisk
43
053
2B
00101011 +
+
Plus
44
054
2C
00101100 ,
,
Comma
45
055
2D
00101101 -
-
Hyphen
46
056
2E
00101110 .
.
47
057
2F
00101111 /
/
Slash or divide
48
060
30
00110000 0
0
Zero
49
061
31
00110001 1
1
One
50
062
32
00110010 2
2
Two
51
063
33
00110011 3
3
Three
52
064
34
00110100 4
4
Four
53
065
35
00110101 5
5
Five
54
066
36
00110110 6
6
Six
55
067
37
00110111 7
7
Seven
56
070
38
00111000 8
8
Eight
274
Perl
57
071
39
00111001 9
9
Nine
58
072
3A
00111010 :
:
Colon
59
073
3B
00111011 ;
;
Semicolon
60
074
3C
00111100 <
<
Less than
61
075
3D
00111101 =
=
Equals
62
076
3E
00111110 >
>
Greater than
63
077
3F
00111111 ?
?
Question mark
64
100
40
01000000 @
@
At symbol
65
101
41
01000001 A
A
Uppercase A
66
102
42
01000010 B
B
Uppercase B
67
103
43
01000011 C
C
Uppercase C
68
104
44
01000100 D
D
Uppercase D
69
105
45
01000101 E
E
Uppercase E
70
106
46
01000110 F
F
Uppercase F
71
107
47
01000111 G
G
Uppercase G
72
110
48
01001000 H
H
Uppercase H
73
111
49
01001001 I
I
Uppercase I
74
112
4A
01001010 J
J
Uppercase J
75
113
4B
01001011 K
K
Uppercase K
76
114
4C
01001100 L
L
Uppercase L
77
115
4D
01001101 M
M
Uppercase M
275
Perl
78
116
4E
01001110 N
N
Uppercase N
79
117
4F
01001111 O
O
Uppercase O
80
120
50
01010000 P
P
Uppercase P
81
121
51
01010001 Q
Q
Uppercase Q
82
122
52
01010010 R
R
Uppercase R
83
123
53
01010011 S
S
Uppercase S
84
124
54
01010100 T
T
Uppercase T
85
125
55
01010101 U
U
Uppercase U
86
126
56
01010110 V
V
Uppercase V
87
127
57
01010111 W
W
Uppercase W
88
130
58
01011000 X
X
Uppercase X
89
131
59
01011001 Y
Y
Uppercase Y
90
132
5A
01011010 Z
Z
Uppercase Z
91
133
5B
01011011 [
[
Opening bracket
92
134
5C
01011100 \
\
Backslash
93
135
5D
01011101 ]
]
Closing bracket
94
136
5E
01011110 ^
^
Caret - circumflex
95
137
5F
01011111 _
_
Underscore
96
140
60
01100000 `
`
Grave accent
97
141
61
01100001 a
a
Lowercase a
98
142
62
01100010 b
b
Lowercase b
276
Perl
99
143
63
01100011 c
c
Lowercase c
100
144
64
01100100 d
d
Lowercase d
101
145
65
01100101 e
e
Lowercase e
102
146
66
01100110 f
f
Lowercase f
103
147
67
01100111 g
g
Lowercase g
104
150
68
01101000 h
h
Lowercase h
105
151
69
01101001 i
i
Lowercase i
106
152
6A
01101010 j
j
Lowercase j
107
153
6B
01101011 k
k
Lowercase k
108
154
6C
01101100 l
l
Lowercase l
109
155
6D
01101101 m
m
Lowercase m
110
156
6E
01101110 n
n
Lowercase n
111
157
6F
01101111 o
o
Lowercase o
112
160
70
01110000 p
p
Lowercase p
113
161
71
01110001 q
q
Lowercase q
114
162
72
01110010 r
r
Lowercase r
115
163
73
01110011 s
s
Lowercase s
116
164
74
01110100 t
t
Lowercase t
117
165
75
01110101 u
u
Lowercase u
118
166
76
01110110 v
v
Lowercase v
119
167
77
01110111 w
w
Lowercase w
277
Perl
120
170
78
01111000 x
x
Lowercase x
121
171
79
01111001 y
y
Lowercase y
122
172
7A
01111010 z
z
Lowercase z
123
173
7B
01111011 {
{
Opening brace
124
174
7C
01111100 |
|
Vertical bar
125
175
7D
01111101 }
}
Closing brace
126
176
7E
01111110 ~
~
127
177
7F
01111111

Delete
BIN
Symbol HTMLCode
128
200
80
10000000
129
201
81
10000001
130
202
82
131
203
132
Description
€
Euro sign
10000010
‚
83
10000011
ƒ
204
84
10000100
„
Double
mark
133
205
85
10000101
…
Horizontal ellipsis
134
206
86
10000110
†
Dagger
135
207
87
10000111
‡
Double dagger
136
210
88
10001000
ˆ
Modifier
accent
low-9
letter
quotation
circumflex
278
Perl
137
211
89
10001001
‰
138
212
8A
10001010
Š
139
213
8B
10001011
‹
Single left-pointing
quotation
140
214
8C
10001100
Œ
141
215
8D
10001101
142
216
8E
10001110
Ž
143
217
8F
10001111
144
220
90
10010000
145
221
91
10010001
‘
146
222
92
10010010
’
147
223
93
10010011
“
148
224
94
10010100
”
149
225
95
10010101
•
Bullet
150
226
96
10010110
–
En dash
151
227
97
10010111
—
Em dash
152
230
98
10011000
˜
Small tilde
153
231
99
10011001
™
154
232
9A
10011010
š
155
233
9B
10011011
›
angle
279
Perl
156
234
9C
10011100
œ
157
235
9D
10011101
158
236
9E
10011110
ž
Latin small
caron
159
237
9F
10011111
Ÿ
160
240
A0
10100000
 
Non-breaking space
161
241
A1
10100001
¡
162
242
A2
10100010
¢
Cent sign
163
243
A3
10100011
£
Pound sign
164
244
A4
10100100
¤
Currency sign
165
245
A5
10100101
¥
Yen sign
166
246
A6
10100110
¦
167
247
A7
10100111
§
Section sign
168
250
A8
10101000
¨
169
251
A9
10101001
©
Copyright sign
170
252
AA
10101010
ª
171
253
AB
10101011
«
172
254
AC
10101100
¬
Not sign
173
255
AD
10101101
­
Soft hyphen
174
256
AE
10101110
®
175
257
AF
10101111
¯
letter
with
280
Perl
176
260
B0
10110000
°
Degree sign
177
261
B1
10110001
±
Plus-or-minus sign
178
262
B2
10110010
²
179
263
B3
10110011
³
180
264
B4
10110100
´
181
265
B5
10110101
µ
Micro sign
182
266
B6
10110110
¶
Pilcrow
sign
sign
paragraph
183
267
B7
10110111
·
Middle
comma
dot
Georgian
184
270
B8
10111000
¸
Spacing cedilla
185
271
B9
10111001
¹
Superscript one
186
272
BA
10111010
º
187
273
BB
10111011
»
188
274
BC
10111100
¼
189
275
BD
10111101
½
190
276
BE
10111110
¾
191
277
BF
10111111
¿
192
300
C0
11000000
À
193
301
C1
11000001
Á
194
302
C2
11000010
Â
281
Perl
195
303
C3
11000011
Ã
196
304
C4
11000100
Ä
197
305
C5
11000101
Å
198
306
C6
11000110
Æ
199
307
C7
11000111
Ç
200
310
C8
11001000
È
201
311
C9
11001001
É
202
312
CA
11001010
Ê
203
313
CB
11001011
Ë
204
314
CC
11001100
Ì
205
315
CD
11001101
Í
206
316
CE
11001110
Î
207
317
CF
11001111
Ï
208
320
D0
11010000
Ð
209
321
D1
11010001
Ñ
282
Perl
210
322
D2
11010010
Ò
211
323
D3
11010011
Ó
212
324
D4
11010100
Ô
213
325
D5
11010101
Õ
214
326
D6
11010110
Ö
215
327
D7
11010111
×
Multiplication sign
216
330
D8
11011000
Ø
217
331
D9
11011001
Ù
218
332
DA
11011010
Ú
219
333
DB
11011011
Û
220
334
DC
11011100
Ü
221
335
DD
11011101
Ý
222
336
DE
11011110
Þ
223
337
DF
11011111
ß
224
340
E0
11100000
à
a with
283
Perl
225
341
E1
11100001
á
a with
226
342
E2
11100010
â
a with
227
343
E3
11100011
ã
228
344
E4
11100100
ä
229
345
E5
11100101
å
230
346
E6
11100110
æ
231
347
E7
11100111
ç
Latin small
cedilla
letter
with
232
350
E8
11101000
è
with
233
351
E9
11101001
é
with
234
352
EA
11101010
ê
with
235
353
EB
11101011
ë
with
236
354
EC
11101100
ì
Latin small
grave
letter
with
237
355
ED
11101101
í
Latin small
acute
letter
with
238
356
EE
11101110
î
Latin small
circumflex
letter
with
239
357
EF
11101111
ï
Latin small
diaeresis
letter
with
a with
284
Perl
240
360
F0
11110000
ð
241
361
F1
11110001
ñ
242
362
F2
11110010
ò
243
363
F3
11110011
ó
244
364
F4
11110100
ô
245
365
F5
11110101
õ
246
366
F6
11110110
ö
247
367
F7
11110111
÷
Division sign
248
370
F8
11111000
ø
249
371
F9
11111001
ù
250
372
FA
11111010
ú
251
373
FB
11111011
û
252
374
FC
11111100
ü
253
375
FD
11111101
ý
Latin small
acute
254
376
FE
11111110
þ
255
377
FF
11111111
ÿ
Latin small
diaeresis
letter y with
letter y with
285
Perl
chroot
Description
This function works like the system call by the same name: it makes the named
directory the new root directory for all further pathnames that begin with a / by
your process and all its children. For security reasons, this function, which is
identical to the system chroot( ) function, is restricted to the superuser and
cannot be undone.
If FILENAME is omitted, then it does a chroot to $_
Syntax
Following is the simple syntax for this function:
chroot EXPR
chroot
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
close
Description
This function closes FILEHANDLE, flushing the buffers, if appropriate, and
disassociating the FILEHANDLE with the original file, pipe, or socket. Closes the
currently selected filehandle if none is specified.
286
Perl
Syntax
Following is the simple syntax for this function:
close FILEHANDLE
close
Return Value
This function returns 0 on failure and 1 if buffers were flushed and the file was
successfully closed.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
closedir
Description
This function closes the directory handle DIRHANDLE.
Syntax
Following is the simple syntax for this function:
closedir DIRHANDLE
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
287
Perl
$dirname = "/tmp";
connect
Description
This function connects to the remote socket using the filehandle SOCKET and the
address specified by EXPR. The EXPR should be a packed address of the
appropriate type for the socket.
Syntax
Following is the simple syntax for this function:
connect SOCKET, EXPR
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage:
288
Perl
continue
Description
This function is a flow control statement rather than a function. If there is a
continue BLOCK attached to a BLOCK (typically in a while or foreach ), it is
always executed just before the conditional is about to be evaluated again, just
like the third part of a for loop in C.
Thus it can be used to increment a loop variable, even when the loop has been
continued via the next statement. last, next, or redo may appear within a
continue block.
Syntax
Following is the simple syntax for this function:
continue BLOCK
Return Value
This function does not return anything.
Example
Following is the example code showing its basic usage:
while (EXPR) {
### redo always comes here
do_something;
} continue {
### next always comes here
do_something_else;
# then back the top to re-check EXPR
}
### last always comes here
When above code is executed, it produces the following result:
289
Perl
cos
Description
This function returns the cosine of EXPR, or $_ if EXPR is omitted. The value
should be expressed in radians.
Syntax
Following is the simple syntax for this function:
cos EXPR
cos
Return Value
This function returns floating point number.
Example
Following is the example code showing its basic usage:
crypt
Description
This function encrypts the string EXPR using the system crypt( ) function. The
value of SALT is used to select an encrypted version from one of a number of
variations.
You cannot decrypt a string that has been encrypted in this way. It's normally
used one way, first to encrypt a string, and then to encrypt a password to
compare against the encrypted string. If you're using it in this form, then
consider supplying the encrypted password as the SALT.
Syntax
Following is the simple syntax for this function:
290
Perl
crypt EXPR,SALT
Return Value
This function returns the encrypted string.
Example
Following is the example code showing its basic usage, it makes sure that
whoever runs this program knows their password::
#!/usr/bin/perl
$pwd = (getpwuid($<))[1];
dbmclose
Description
This function closes the binding between a hash and a DBM file. Use the tie
function with a suitable module.
291
Perl
Syntax
Following is the simple syntax for this function:
dbmclose HASH
Return Value
This function returns 0 on failure and 1 on success.
Note that functions such as keys and values may return huge lists when used on
large DBM files. You may prefer to use the each function to iterate over large
DBM files.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
dbmopen
Description
This function Binds the database file specified by EXPR to the hash HASH. If the
database does not exist, then it is created using the mode specified by MODE.
The file EXPR should be specified without the .dir and .pag extensions. Use is
now deprecated in favor of tie and one of the tied DBM hash modules, such
as SDBM_File.
Syntax
Following is the simple syntax for this function:
292
Perl
Return Value
This function returns 0 on failure and 1 on success.
Note that functions such as keys and values may return huge lists when used on
large DBM files. You may prefer to use the each function to iterate over large
DBM files.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
defined
Description
This function returns true if EXPR has a value other than the undef value, or
checks the value of $_ if EXPR is not specified. This can be used with many
functions to detect a failure in operation, since they return undef if there was a
problem. A simple Boolean test does not differentiate between false, zero, an
empty string, or the string .0., which are all equally false.
If EXPR is a function or function reference, then it returns true if the function has
been defined. When used with entire arrays and hashes, it will not always
produce intuitive results. If a hash element is specified, it returns true if the
corresponding value has been defined, but does not determine whether the
specified key exists in the hash.
293
Perl
Syntax
Following is the simple syntax for this function:
defined EXPR
defined
Return Value
This function returns 0 if EXPR contains undef and 1 if EXPR contains a valid
value or reference.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
if( defined($var1) ){
print "$var1\n";
}
if( defined($var2) ){
print "var2 is also defined\n";
}else{
print "var2 is not defined\n";
}
When above code is executed, it produces the following result:
This is defined
var2 is not defined
294
Perl
delete
Description
This function deletes the specified keys and associated values from a hash, or
the specified elements from an array. The operation works on individual
elements or slices.
Syntax
Following is the simple syntax for this function:
delete LIST
Return Value
This function returns undef if the key does not exist and value associated with
the deleted hash key or array index.
Example
Following is the example code showing its basic usage, it deletes all the values
of %HASH and @ARRAY:
die
Description
This function prints the value of LIST to STDERR and calls exit with the error
value contained in $!.
Syntax
Following is the simple syntax for this function:
die LIST
295
Perl
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
do
Description
This function when supplied a block, do executes as if BLOCK were a function,
returning the value of the last statement evaluated in the block.
When supplied with EXPR, do executes the file specified by EXPR as if it were
another Perl script.
If supplied a subroutine, SUB, do executes the subroutine using LIST as the
arguments, raising an exception if SUB hasn.t been defined.
Syntax
Following is the simple syntax for this function:
do BLOCK
do EXPR
do SUB(LIST)
Return Value
This function returns the value of the last statement evaluated in the block.
Example
Following is the example code showing its basic usage:
296
Perl
dump
Description
This function Dumps the currently executing Perl interpreter and script into a
core dump. Using the undump program, you can then reconstitute the dumped
core into an executable program.
When the new binary is executed it will begin by executing a goto LABEL. If
LABEL is omitted, restarts the program from the top.
If you're looking to use dump to speed up your program, consider generating
bytecode or native C code as described in perlcc. The perlcc generates
executables from Perl programs and this compiler comes alongwith PERL
installation.
Syntax
Following is the simple syntax for this function:
dump LABEL
dump
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
297
Perl
each
Description
This function when called in list context, returns a 2-element list consisting of
the key and value for the next element of a hash, so that you can iterate over it.
When called in scalar context, returns only the key for the next element in the
hash.
Syntax
Following is the simple syntax for this function:
each HASH
Return Value
This function when called in list context, returns a 2-element list consisting of
the key and value for the next element of a hash, so that you can iterate over it.
It returns only the key for the next element in the hash when called in scalar
context.
Example
Following is the example code showing its basic usage, this will print out all
environment variables.:
endgrent
Description
This function tells the system you no longer expect to read entries from the
groups file using getgrent.
Syntax
Following is the simple syntax for this function:
endgrent
298
Perl
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
endhostent
Description
This function tells the system you no longer expect to read entries from the
hosts file using gethostent.
Syntax
Following is the simple syntax for this function:
endhostent
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
= $name\n";
print "Aliases
= $aliases\n";
= $addrtype\n";
= $length\n";
= @addrs\n";
}
299
Perl
sethostent(1);
= $name\n";
print "Aliases
= $aliases\n";
= $addrtype\n";
= $length\n";
= @addrs\n";
endhostent();
= ip-50-62-147-141.ip.secureserver.net
= 2
= 4
=
= ip-50-62-147-141.ip.secureserver.net
= 2
= 4
=
endnetent
Description
This function tells the system you no longer expect to read entries from the
networks list using getnetent.
300
Perl
Syntax
Following is the simple syntax for this function:
endnetent
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
use Socket;
= getnetent() ){
= getnetent() ){
endnetent();
Perl
Name = default
Aliases =
Addrtype = 2
Net = 0
Name = loopback
Aliases =
Addrtype = 2
Net = 2130706432
Name = link-local
Aliases =
Addrtype = 2
Net = 2851995648
Name = default
Aliases =
Addrtype = 2
Net = 0
Name = loopback
Aliases =
Addrtype = 2
Net = 2130706432
Name = link-local
Aliases =
Addrtype = 2
Net = 2851995648
endprotoent
Description
This function tells the system you no longer expect to read entries from the
protocols list using getprotoent.
Syntax
Following is the simple syntax for this function:
302
Perl
endprotoent
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
Perl
Name = igmp
Aliases = IGMP
Protocol Number = 2
Name = ggp
Aliases = GGP
Protocol Number = 3
Name = ipencap
Aliases = IP-ENCAP
Protocol Number = 4
Name = st
Aliases = ST
Protocol Number = 5
Name = tcp
Aliases = TCP
Protocol Number = 6
.
.
.
Name = manet
Aliases = manet
Protocol Number = 138
Name = hip
Aliases = HIP
Protocol Number = 139
Name = shim6
Aliases = Shim6
Protocol Number = 140
endpwent
Description
This function tells the system you no longer expect to read entries from the
password file using getpwent. Under Windows, use the Win32API::Net function
to get the information from a domain server.
304
Perl
Syntax
Following is the simple syntax for this function:
endpwent
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
Perl
Perl
Perl
Quota =
Comment =
Gcos = shutdown
HOME DIR = /sbin
Shell = /sbin/shutdown
Name = halt
Password = x
UID = 7
GID = 0
Quota =
Comment =
Gcos = halt
HOME DIR = /sbin
Shell = /sbin/halt
Name = mail
Password = x
UID = 8
GID = 12
Quota =
Comment =
Gcos = mail
HOME DIR = /var/spool/mail
Shell = /sbin/nologin
Name = uucp
Password = x
UID = 10
GID = 14
Quota =
Comment =
Gcos = uucp
HOME DIR = /var/spool/uucp
Shell = /sbin/nologin
Name = operator
308
Perl
Password = x
UID = 11
GID = 0
Quota =
Comment =
Gcos = operator
HOME DIR = /root
Shell = /sbin/nologin
Name = games
Password = x
UID = 12
GID = 100
Quota =
Comment =
Gcos = games
HOME DIR = /usr/games
Shell = /sbin/nologin
Name = gopher
Password = x
UID = 13
GID = 30
Quota =
Comment =
Gcos = gopher
HOME DIR = /var/gopher
Shell = /sbin/nologin
Name = ftp
Password = x
UID = 14
GID = 50
Quota =
Comment =
Gcos = FTP User
309
Perl
Perl
Quota =
Comment =
Gcos = Rpcbind Daemon
HOME DIR = /var/cache/rpcbind
Shell = /sbin/nologin
Name = abrt
Password = x
UID = 173
GID = 173
Quota =
Comment =
Gcos =
HOME DIR = /etc/abrt
Shell = /sbin/nologin
Name = apache
Password = x
UID = 48
GID = 48
Quota =
Comment =
Gcos = Apache
HOME DIR = /var/www
Shell = /sbin/nologin
Name = saslauth
Password = x
UID = 499
GID = 76
Quota =
Comment =
Gcos = "Saslauthd user"
HOME DIR = /var/empty/saslauth
Shell = /sbin/nologin
Name = postfix
311
Perl
Password = x
UID = 89
GID = 89
Quota =
Comment =
Gcos =
HOME DIR = /var/spool/postfix
Shell = /sbin/nologin
Name = qpidd
Password = x
UID = 498
GID = 499
Quota =
Comment =
Gcos = Owner of Qpidd Daemons
HOME DIR = /var/lib/qpidd
Shell = /sbin/nologin
Name = haldaemon
Password = x
UID = 68
GID = 68
Quota =
Comment =
Gcos = HAL daemon
HOME DIR = /
Shell = /sbin/nologin
Name = ntp
Password = x
UID = 38
GID = 38
Quota =
Comment =
Gcos =
312
Perl
Perl
Quota =
Comment =
Gcos = Webalizer
HOME DIR = /var/www/usage
Shell = /sbin/nologin
Name = sshd
Password = x
UID = 74
GID = 74
Quota =
Comment =
Gcos = Privilege-separated SSH
HOME DIR = /var/empty/sshd
Shell = /sbin/nologin
Name = tcpdump
Password = x
UID = 72
GID = 72
Quota =
Comment =
Gcos =
HOME DIR = /
Shell = /sbin/nologin
Name = oprofile
Password = x
UID = 16
GID = 16
Quota =
Comment =
Gcos = Special user account to be used by OProfile
HOME DIR = /home/oprofile
Shell = /sbin/nologin
Name = amrood
314
Perl
Password = x
UID = 500
GID = 500
Quota =
Comment =
Gcos =
HOME DIR = /home/amrood
Shell = /bin/bash
Name = mailnull
Password = x
UID = 47
GID = 47
Quota =
Comment =
Gcos =
HOME DIR = /var/spool/mqueue
Shell = /sbin/nologin
Name = smmsp
Password = x
UID = 51
GID = 51
Quota =
Comment =
Gcos =
HOME DIR = /var/spool/mqueue
Shell = /sbin/nologin
Name = mysql
Password = x
UID = 27
GID = 27
Quota =
Comment =
Gcos = MySQL Server
315
Perl
Perl
Quota =
Comment =
Gcos =
HOME DIR = /opt/railo
Shell = /bin/false
Name = root
Password = x
UID = 0
GID = 0
Quota =
Comment =
Gcos = root
HOME DIR = /root
Shell = /bin/bash
Name = bin
Password = x
UID = 1
GID = 1
Quota =
Comment =
Gcos = bin
HOME DIR = /bin
Shell = /sbin/nologin
Name = daemon
Password = x
UID = 2
GID = 2
Quota =
Comment =
Gcos = daemon
HOME DIR = /sbin
Shell = /sbin/nologin
Name = adm
317
Perl
Password = x
UID = 3
GID = 4
Quota =
Comment =
Gcos = adm
HOME DIR = /var/adm
Shell = /sbin/nologin
Name = lp
Password = x
UID = 4
GID = 7
Quota =
Comment =
Gcos = lp
HOME DIR = /var/spool/lpd
Shell = /sbin/nologin
Name = sync
Password = x
UID = 5
GID = 0
Quota =
Comment =
Gcos = sync
HOME DIR = /sbin
Shell = /bin/sync
Name = shutdown
Password = x
UID = 6
GID = 0
Quota =
Comment =
Gcos = shutdown
318
Perl
Perl
Quota =
Comment =
Gcos = operator
HOME DIR = /root
Shell = /sbin/nologin
Name = games
Password = x
UID = 12
GID = 100
Quota =
Comment =
Gcos = games
HOME DIR = /usr/games
Shell = /sbin/nologin
Name = gopher
Password = x
UID = 13
GID = 30
Quota =
Comment =
Gcos = gopher
HOME DIR = /var/gopher
Shell = /sbin/nologin
Name = ftp
Password = x
UID = 14
GID = 50
Quota =
Comment =
Gcos = FTP User
HOME DIR = /var/ftp
Shell = /sbin/nologin
Name = nobody
320
Perl
Password = x
UID = 99
GID = 99
Quota =
Comment =
Gcos = Nobody
HOME DIR = /
Shell = /sbin/nologin
Name = dbus
Password = x
UID = 81
GID = 81
Quota =
Comment =
Gcos = System message bus
HOME DIR = /
Shell = /sbin/nologin
Name = vcsa
Password = x
UID = 69
GID = 69
Quota =
Comment =
Gcos = virtual console memory owner
HOME DIR = /dev
Shell = /sbin/nologin
Name = rpc
Password = x
UID = 32
GID = 32
Quota =
Comment =
Gcos = Rpcbind Daemon
321
Perl
Perl
Quota =
Comment =
Gcos =
HOME DIR = /var/spool/postfix
Shell = /sbin/nologin
Name = qpidd
Password = x
UID = 498
GID = 499
Quota =
Comment =
Gcos = Owner of Qpidd Daemons
HOME DIR = /var/lib/qpidd
Shell = /sbin/nologin
Name = haldaemon
Password = x
UID = 68
GID = 68
Quota =
Comment =
Gcos = HAL daemon
HOME DIR = /
Shell = /sbin/nologin
Name = ntp
Password = x
UID = 38
GID = 38
Quota =
Comment =
Gcos =
HOME DIR = /etc/ntp
Shell = /sbin/nologin
Name = rpcuser
323
Perl
Password = x
UID = 29
GID = 29
Quota =
Comment =
Gcos = RPC Service User
HOME DIR = /var/lib/nfs
Shell = /sbin/nologin
Name = nfsnobody
Password = x
UID = 65534
GID = 65534
Quota =
Comment =
Gcos = Anonymous NFS User
HOME DIR = /var/lib/nfs
Shell = /sbin/nologin
Name = tomcat
Password = x
UID = 91
GID = 91
Quota =
Comment =
Gcos = Apache Tomcat
HOME DIR = /usr/share/tomcat6
Shell = /sbin/nologin
Name = webalizer
Password = x
UID = 67
GID = 67
Quota =
Comment =
Gcos = Webalizer
324
Perl
Perl
Quota =
Comment =
Gcos =
HOME DIR = /home/amrood
Shell = /bin/bash
Name = mailnull
Password = x
UID = 47
GID = 47
Quota =
Comment =
Gcos =
HOME DIR = /var/spool/mqueue
Shell = /sbin/nologin
Name = smmsp
Password = x
UID = 51
GID = 51
Quota =
Comment =
Gcos =
HOME DIR = /var/spool/mqueue
Shell = /sbin/nologin
Name = mysql
Password = x
UID = 27
GID = 27
Quota =
Comment =
Gcos = MySQL Server
HOME DIR = /var/lib/mysql
Shell = /bin/bash
Name = named
326
Perl
Password = x
UID = 25
GID = 25
Quota =
Comment =
Gcos = Named
HOME DIR = /var/named
Shell = /sbin/nologin
Name = qemu
Password = x
UID = 107
GID = 107
Quota =
Comment =
Gcos = qemu user
HOME DIR = /
Shell = /sbin/nologin
Name = com
Password = x
UID = 501
GID = 501
Quota =
Comment =
Gcos =
HOME DIR = /home/com
Shell = /bin/bash
Name = railo
Password = x
UID = 497
GID = 495
Quota =
Comment =
Gcos =
327
Perl
endservent
Description
This function tells the system you no longer expect to read entries from the
services file using getservent.
Syntax
Following is the simple syntax for this function:
endservent
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
setservent();
Perl
endservent();
eof
Description
This function returns 1 if the next read on FILEHANDLE will return end of file, or
if FILEHANDLE is not open.
An eof without an argument uses the last file read. Using eof() with empty
parentheses is very different. It refers to the pseudo file formed from the files
listed on the command line and accessed via the <> operator.
Syntax
Following is the simple syntax for this function:
eof FILEHANDLE
eof()
eof
Return Value
This function returns undef if FILEHANDLE is not at end of file and 1 if
FILEHANDLE will report end of file on next read.
Example
Following is the example code showing its basic usage:
329
Perl
print "--------------\n";
}
print;
last if eof();
}
When above code is executed, it produces the following result:
eval
Description
This function evaluates EXPR at execution time as if EXPR were a separate Perl
script. This allows you to use a separate, perhaps user-supplied, piece of Perl
script within your program. An eval EXPR statement is evaluated separately each
time the function is called.
The second form evaluates BLOCK when the rest of the script is parsed (before
execution).
Syntax
Following is the simple syntax for this function:
eval EXPR
eval BLOCK
Return Value
This function returns value of last evaluated statement in EXPR or BLOCK
Example
Following is the example code showing its basic usage:
330
Perl
exec
Description
This function executes a system command (directly, not within a shell) and
never returns to the calling script, except if the command specified does not
exist and has been called directly, instead of indirectly through a shell. The
operation works as follows:
If there is only one scalar argument that contains no shell metacharacters, then
the argument is converted into a list and the command is executed directly,
without a shell.
If there is only one scalar argument that contains shell metacharacters, then the
argument is executed through the standard shell, usually /bin/sh on Unix.
If LIST is more than one argument, or an array with more than one value, then
the command is executed directly without the use of a shell.
Syntax
Following is the simple syntax for this function:
exec EXPR LIST
exec LIST
Return Value
This function returns 0 only if the command specified cannot be executed.
Example
Following is the example code showing its basic usage:
331
Perl
exists
Description
This function returns true if the specified hash or array key exists, regardless of
the corresponding value, even if it.s undef. If EXPR is a subroutine, then exists
will return 1 if the subroutine has been declared (but not necessarily defined), 0
if not.
If LIST is more than one argument, or an array with more than one value, then
the command is executed directly without the use of a shell.
Syntax
Following is the simple syntax for this function:
exists EXPR
Return Value
This function returns 0 if hash element or array index does not exist, or if the
subroutine has not been declared and 1 if hash element or array index does
exist, or if the subroutine has not been declared.
Example
Following is the example code showing its basic usage:
exit
Description
This function evaluates EXPR, exits the Perl interpreter, and returns the value as
the exit value.Always runs all END{} blocks defined in the script (and imported
packages) before exiting. If EXPR is omitted, then the interpreter exits with a
value of 0. Should not be used to exit from a subroutine; either use eval and die
or use return.
332
Perl
Syntax
Following is the simple syntax for this function:
exit EXPR
exit
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
exp
Description
This function returns e (the natural logarithm base) to the power of EXPR. If
EXPR is omitted, gives exp($_).
Syntax
Following is the simple syntax for this function:
exp EXPR
exp
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
333
Perl
fcntl
Description
This function is the Perl version of the system fcntl( ) function. Performs the
function specified by FUNCTION, using SCALAR on FILEHANDLE. SCALAR either
contains a value to be used by the function or is the location of any returned
information.
Syntax
Following is the simple syntax for this function:
fcntl FILEHANDLE, FUNCTION, SCALAR
Return Value
This function returns 0 but true if the return value from the fcntl()is 0 Value
returned by system and undef on failure.
Example
Following is the example code showing its basic usage:
fileno
Description
This function returns the file descriptor number (as used by C and POSIX
functions) of the specified FILEHANDLE. This is generally useful only for using
the select function and any low-level tty functions.
334
Perl
Syntax
Following is the simple syntax for this function:
fileno FILEHANDLE
Return Value
This function returns File descriptor (numeric) of FILEHANDLE and undef on
failure.
Example
flock
Description
This function supports file locking on the specified FILEHANDLE using the system
flock( ), fcntl( ) locking, or lockf( ). The exact implementation used is dependent
on what your system supports. OPERATION is one of the static values defined
here.
Operation Result
LOCK_SH
LOCK_EX
LOCK_UN
LONG_NB
Syntax
Following is the simple syntax for this function:
flock FILEHANDLE, OPERATION
335
Perl
Return Value
This function returns 0 on failure to set/unset lock and 1 on success to set/unset
lock.
Example
Following is the example code showing its basic usage:
fork
Description
This function forks a new process using the fork( ) system call. Any shared
sockets or filehandles are duplicated across processes. You must ensure that you
wait on your children to prevent "zombie" processes from forming.
Syntax
Following is the simple syntax for this function:
fork
Return Value
This function returns undef on failure to fork and Child process ID to parent on
success 0 to child on success.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
$pid = fork();
if( $pid == 0 ){
print "This is child process\n";
print "Child process is existing\n";
exit 0;
336
Perl
}
print "This is parent process and child ID is $pid\n";
print "Parent process is existing\n";
exit 0;
When above code is executed, it produces the following result:
This is parent process and child ID is 18641
Parent process is existing
This is child process
Child process is existing
format
As stated earlier that Perl stands for Practical Extraction and Reporting
Language, and we'll now discuss using Perl to write reports.
Perl uses a writing template called a 'format' to output reports. To use the
format feature of Perl, you must:
Define a Format
Define a Format
Following is the syntax to define a Perl format
format FormatName =
fieldline
value_one, value_two, value_three
fieldline
value_one, value_two
.
FormatName represents the name of the format. The fieldline is the specific way
the data should be formatted. The values lines represent the values that will be
entered into the field line. You end the format with a single period.
fieldline can contain any text or fieldholders. Fieldholders hold space for data
that will be placed there at a later date. A fieldholder has the format:
337
Perl
@<<<<
This fieldholder is left-justified, with a field space of 5. You must count the @
sign and the < signs to know the number of spaces in the field. Other field
holders include:
@>>>> right-justified
@|||| centered
@####.## numeric field holder
@* multiline field holder
An example format would be:
format EMPLOYEE =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<<
$name $age
@#####.##
$salary
===================================
.
In this example $name would be written as left justify within 22 character
spaces and after that age will be written in two spaces.
338
Perl
$~ = "EMPLOYEE";
When we now do a write(), the data would be sent to STDOUT. Remember: if
you didn't have STDOUT set as your default file handle, you could revert back to
the original file handle by assigning the return value of select to a scalar value,
and using select along with this scalar variable after the special variable is
assigned the format name, to be associated with STDOUT.
The above example will generate a report in the following format
Kirsten
12
Mohammad
35
Suhi
15
Namrat
10
Age
-----------------------.
Now your report will look like
-----------------------Name
Age
-----------------------Kirsten
12
Mohammad
35
Suhi
15
Namrat
10
339
Perl
Age
Page @<
------------------------
$%
.
Now your output will look like
-----------------------Name
Age
Page 1
-----------------------Kirsten
12
Mohammad
35
Suhi
15
Namrat
10
You can set the number of lines per page using special variable $= ( or
$FORMAT_LINES_PER_PAGE ) By default $= will be 60
Age
Page 1
-----------------------Kirsten
12
340
Perl
Mohammad
35
Suhi
15
Namrat
10
End of Page 1
For a complete set of variables related to formating, please refer to Perl Special
Variablessection.
formline
Description
This function is used by the format function and related operators. It formats
LIST according to the contents of PICTURE into the output accumulator variable
$^A. The value is written out to a filehandle when a write is done.
Syntax
Following is the simple syntax for this function:
formline PICTURE, LIST
Return Value
This function always returns 1.
Example
Following is the example code showing its basic usage:
getc
Description
This function reads the next character from FILEHANDLE (or STDIN if none
specified), returning the value.
341
Perl
Syntax
Following is the simple syntax for this function:
getc FILEHANDLE
getc
Return Value
This function returns undef on error or end of file and value of character read
from FILEHANDLE.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
$key = getc(STDIN);
print "Entered value is $key\n";
When above code is executed, it produces the following result:
Entered value is 4
getgrent
Description
This function iterates over the entries in the /etc/group file. Returns the
following in a list context:
($name, $passwd, $gid, $members)
The $members scalar contains a space-separated list of the login names that are
members of the group. Returns the group name only when used in a scalar
context. Under Windows, consider using the Win32API::Net module.
Syntax
Following is the simple syntax for this function:
getgrent
342
Perl
Return Value
This function returns Group name in scalr context and in list context (Name,
Password, Group ID, and member list.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
= $name\n";
print "Password
print "GID
= $passwd\n";
= $gid\n";
print "Members
= $members\n";
}
When above code is executed, it produces the following result:
Name
= root
Password
GID
= 0
Members
Name
= x
= 3
Members
Name
= sys
Password
GID
= x
= 2
Members
Name
= daemon
Password
GID
= x
= 1
Members
Name
= root
= bin
Password
GID
= x
= adm
Password
= x
343
Perl
GID
= 4
Members
Name
= tty
Password
GID
= x
= 5
Members
.
.
.
Name
= fuse
Password
GID
= 496
Members
Name
= x
= kvm
Password
GID
= 36
Members
Name
= com
= railo
Password
GID
= x
= 502
Members
Name
= webgrp
Password
GID
= x
= 501
Members
Name
= com
Password
GID
= x
= 107
Members
Name
= qemu
= qemu
Password
GID
= x
= x
= 495
Members
=
344
Perl
getgrgid
Description
This function looks up the group file entry by group ID. Returns the following in
a list context:
($name, $passwd, $gid, $members)
The $members scalar contains a space-separated list of the login names that are
members of the group. Returns the group name in a scalar context. For a more
efficient method of retrieving the entire groups file, see getgrent. Under
Windows, consider using the Win32API::Net module.
Syntax
Following is the simple syntax for this function:
getgrgid GID
Return Value
This function returns In scalr context it returns Group name and in list context
(Name, Password, Group ID, and member list.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
= $name\n";
print "Password
print "GID
= $passwd\n";
= $gid\n";
print "Members
= $members\n";
}
When above code is executed, it produces the following result:
Name
= root
Password
GID
= x
= 0
345
Perl
Members
Name
= root
Password
GID
= root
= root
Password
GID
= x
= 0
Members
Name
= root
= root
Password
GID
= x
= 0
Members
Name
= root
= root
Password
GID
= x
= 0
Members
Name
= root
= x
= 0
Members
= root
.
.
.
Name
= root
Password
GID
= 0
Members
Name
= x
= 0
Members
Name
= root
= root
Password
GID
= x
= 0
Members
Name
= root
= root
Password
GID
= x
= root
= root
346
Perl
Password
GID
= 0
Members
Name
= root
= root
Password
GID
= x
= x
= 0
Members
= root
getgrnam
Description
This function looks up the group file entry by group name. Returns the following
in a list context: ($name, $passwd, $gid, $members)
The $members scalar contains a space-separated list of the login names that are
members of the group. Returns the group name in a scalar context. For a more
efficient method of retrieving the entire groups file, see getgrent. Under
Windows, consider using the Win32API::Net module.
Syntax
Following is the simple syntax for this function:
getgrnam NAME
Return Value
This function returns Group name in scalr context and Name, Password, Group
ID, and member list in list context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
= $name\n";
print "Password
= $passwd\n";
347
Perl
print "GID
= $gid\n";
print "Members
= $members\n";
}
When above code is executed, it produces the following result
Name
= root
Password
GID
= 0
Members
Name
= root
= root
Password
GID
= x
= 0
Members
Name
= root
= root
Password
GID
= x
= x
= 0
.
.
.
Name
= root
Password
GID
= 0
Members
Name
= x
= 0
Members
Name
= root
= root
Password
GID
= x
= root
= root
348
Perl
gethostbyaddr
Description
This function Contacts the system's name-resolving service, returning a list of
information for the host ADDR of type ADDRTYPE, as follows: ($name, $aliases,
$addrtype, $length, @addrs)
The @addrs array contains a list of packed binary addresses. In a scalar context,
returns the host address.
Syntax
Following is the simple syntax for this function:
gethostbyaddr ADDR, ADDRTYPE
Return Value
This function returns undef on error and otherwise host name in scalr context
and empty list on error otherwise host record in list context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
use Socket;
= gethostbyaddr($iaddr, AF_INET);
gethostbyname
Description
This function contacts the system's name-resolving service, returning a list of
information for the host ADDR of type ADDRTYPE, as follows: ($name, $aliases,
$addrtype, $length, @addrs)
349
Perl
The @addrs array contains a list of packed binary addresses. In a scalar context,
returns the host address.
Syntax
Following is the simple syntax for this function:
gethostbyname NAME
Return Value
This function returns undef on error and otherwise host name in scalr context
and empty list on error otherwise host record in list context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
use Socket;
gethostent
Description
This function iterates over the entries in the host file. It returns the following in
a list context: ($name, $aliases, $addrtype, $length, @addrs)
Syntax
Following is the simple syntax for this function:
gethostent
350
Perl
Return Value
This function returns undef on error and otherwise host name in scalr context
and empty list on error otherwise host record(name, aliases, address type,
length, list of addresses) in list context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
= $name\n";
print "Aliases
= $aliases\n";
= $addrtype\n";
= $length\n";
= @addrs\n";
}
When above code is executed, it produces the following result
Name
= ip-50-62-147-141.ip.secureserver.net
= 2
= 4
=
getlogin
Description
This function returns the user's name, as discovered by the system function
getlogin( ). Under Windows, use the Win32::LoginName( ) function instead.
Syntax
Following is the simple syntax for this function:
getlogin
351
Perl
Return Value
This function returns undef on failure and user's login name on success.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
getnetbyaddr
Description
This function returns the information for the network specified by ADDR and type
ADDRTYPE in a list context: ($name, $aliases, $addrtype, $net)
Syntax
Following is the simple syntax for this function:
getnetbyaddr ADDR, ADDRTYPE
Return Value
This function returns undef on error otherwise Network address in scalar context
and empty list on error otherwise Network record (name, aliases, address type,
network address) in list context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
use Socket;
352
Perl
= getnetbyaddr($iaddr, AF_INET);
getnetbyname
Description
This function returns the information for the network specified by NAME(in list
context) ($name, $aliases, $addrtype, $net)
Syntax
Following is the simple syntax for this function:
getnetbyname NAME
Return Value
This function returns undef on error otherwise Network address in scalar context
and empty list on error otherwise Network record (name, aliases, address type,
network address) in list context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
use Socket;
353
Perl
= getnetbyname("loopback");
getnetent
Description
This function gets the next entry from the /etc/networks file, returning: ($name,
$aliases, $addrtype, $net)
If /etc/networks file is empty then it would not return anything and call will fail..
Syntax
Following is the simple syntax for this function:
getnetent
Return Value
This function returns undef on error otherwise Network address in scalar context
and empty list on error otherwise Network record (name, aliases, address type,
network address) in list context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
354
Perl
use Socket;
= getnetent() ){
getpeername
Description
This function returns the packed socket address of the remote host attached to
SOCKET.
Syntax
Following is the simple syntax for this function:
getpeername SOCKET
355
Perl
Return Value
This function returns undef on error otherwise packed socket address in scalar
context.
Example
Following is the example code showing its basic usage, here SOCK is the socket
ID of the peer socket:
#!/usr/bin/perl
use Socket;
$hersockaddr
= getpeername(SOCK);
= gethostbyaddr($iaddr, AF_INET);
$herstraddr
= inet_ntoa($iaddr);
getpgrp
Description
This function returns the process group for the process ID specified by EXPR, or
the current process group if none is specified.
Syntax
Following is the simple syntax for this function:
getpgrp EXPR
getpgrp
Return Value
This function returns process group ID.
Example
356
Perl
$pgid = getpgrp();
getppid
Description
This function returns the process ID of the parent process.
Syntax
Following is the simple syntax for this function:
getppid
Return Value
This function returns process ID of the parent process.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
$ppid = getppid();
357
Perl
getpriority
Description
This function returns the current priority for a process (PRIO_PROCESS), process
group (PRIO_PGRP) or user (PRIO_USER).
The argument WHICH specifies what entity to set the priority for one of
PRIO_PROCESS, PRIO_PGRP, or PRIO_USER, and WHO is the process ID or user
ID to set. A value of 0 for WHO defines the current process, process group, or
user. This produces a fatal error on systems that don.t support the system
getpriority( ) function.
Syntax
Following is the simple syntax for this function:
getpriority WHICH, WHO
Return Value
This function returns undef on error otherwise current priority.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
When above code is executed, it produces the following result
getprotobyname
Description
This function translates the protocol NAME into its corresponding number in a
scalar context, and its number and associated information in a list
context:($name, $aliases, $protocol_number)
Syntax
Following is the simple syntax for this function:
getprotobyname NAME
358
Perl
Return Value
This function returns undef on error otherwise protocol number in scalar context
and empty list on error protocol record (name, aliases, protocol number) in list
context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
getprotobynumber
Description
This function translates the protocol NUMBER into its corresponding name in a
scalar context, and its name and associated information in a list
context:($name, $aliases, $protocol_number).
Syntax
Following is the simple syntax for this function:
getprotobynumber NUMBER
Return Value
This function returns undef on error otherwise protocol number in scalar context
and empty list on error protocol record (name, aliases, protocol number) in list
context.
359
Perl
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
getprotoent
Description
This function returns the next entry from the list of valid protocols: ($name,
$aliases, $protocol_number)
Syntax
Following is the simple syntax for this function:
getprotoent
Return Value
This function returns undef on error otherwise protocol number in scalar context
and empty list on error protocol record (name, aliases, protocol number) in list
context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
360
Perl
Perl
Name = manet
Aliases = manet
Protocol Number = 138
Name = hip
Aliases = HIP
Protocol Number = 139
Name = shim6
Aliases = Shim6
Protocol Number = 140
getpwent
Description
This function returns the next password entry from the /etc/passwd file. This is
used in combination with the setpwent and endpwent functions to iterate over
the password file. In a list context, returns
($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) =
getpwent;
Syntax
Following is the simple syntax for this function:
getpwent
Return Value
This function returns username in scalar context and user record (name,
password, user ID, group ID, quote, comment, real name, home directory, shell)
in list context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
Perl
Perl
Password = x
UID = 501
GID = 501
Quota =
Comment =
Gcos =
HOME DIR = /home/com
Shell = /bin/bash
Name = railo
Password = x
UID = 497
GID = 495
Quota =
Comment =
Gcos =
HOME DIR = /opt/railo
getpwnam
Description
This function returns a list of fields In list context, as extracted from the
/etc/passwd file, based on the user name specified by EXPR. It's generally used
like this:
($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) =
getpwnam ($user);
In a scalar context, returns the numeric user ID. If you are trying to access the
whole /etc/passwd file, you should use the getpwent function. If you want to
access the details by user ID, use getpwuid.
Syntax
Following is the simple syntax for this function:
getpwnam EXPR
364
Perl
Return Value
This function returns user ID in scalar context and user record (name, password,
user ID, group ID, quote, comment, real name, home directory, shell) in list
context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
365
Perl
getpwuid
Description
This function returns a list of fields in list context, as extracted from the
/etc/passwd file, based on the user name specified by EXPR. It.s generally used
like this:
($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) =
getpwuid ($uid);
In a scalar context, returns the user name. If you are trying to access the whole
/etc/passwd file, you should use the getpwent function. If you want to access
the details by user name, use getpwnam.
Syntax
Following is the simple syntax for this function:
getpwuid EXPR
Return Value
This function returns user Name in scalar context and user record (name,
password, user ID, group ID, quote, comment, real name, home directory, shell)
in list context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
Perl
getservbyname
Description
This function Translates the service NAME for the protocol PROTO, returning the
service number in a scalar context and the number and associated information in
a list context:
($name, $aliases, $port_number, $protocol_name)
This call returns these values based on /etc/services file.
Syntax
Following is the simple syntax for this function:
getservbyname NAME, PROTO
Return Value
This function returns undef on error otherwise service number in scalar context
and empty list on error otherwise Service record (name, aliases, port number,
protocol name) in list context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
367
Perl
getservbyport
Description
This function Translates the service number PORT for the protocol PROTO,
returning the service name in a scalar context and the name and associated
information in a list context:
($name, $aliases, $port_number, $protocol_name)
This call returns these values based on /etc/services file.
Syntax
Following is the simple syntax for this function:
getservbyport PORT, PROTO
Return Value
This function returns undef on error otherwise service number in scalar context
and empty list on error otherwise Service record (name, aliases, port number,
protocol name) in list context.
Example
Following is the example code showing its basic usage:
368
Perl
#!/usr/bin/perl
getservent
Description
This function gets the next entry from the list of service entries, returning:
($name, $aliases, $port_number, $protocol_name)
This call iterate through /etc/services file.
Syntax
Following is the simple syntax for this function:
getservent
Return Value
This function returns undef on error otherwise service name in scalar context
and empty list on error otherwise Service record (name, aliases, port number,
protocol name) in list context.
Example
Following is the example code showing its basic usage:
369
Perl
#!/usr/bin/perl
Perl
getsockname
Description
This function returns a packed address of the local end of the network socket
SOCKET.
Syntax
Following is the simple syntax for this function:
getsockname SOCKET
Return Value
This function returns undef on error otherwise Packed address of local socket in
scalar cotext.
Example
Following is the example code showing its basic usage:
Perl
getsockopt
Description
This function gets the socket options set on SOCKET at the socket
implementation level LEVEL for the option OPTNAME. Some sample values for
OPTNAME at a socket level are given in Table below:
OPTNAME
Result
SO_DEBUG
SO_REUSEADDR
SO_KEEPALIVE
SO_DONTROUTE
SO_OOBINLINE
SO_ERROR
TCP_NODELAY
What exactly is in the packed string depends in the LEVEL and OPTNAME,
consult your system documentation for details.
Syntax
Following is the simple syntax for this function:
getsockopt SOCKET, LEVEL, OPTNAME
Return Value
This function returns undef on error otherwise option value in scalar context.
Example
372
Perl
Following is the example code showing its basic usage, this will check if Nagle's
algorithm is turned on on a socket. But, here you would have to open one socket
to provide socked ID in this example:
#!/usr/bin/perl
glob
Description
This function returns a list of files matching EXPR as they would be expanded by
the standard Bourne shell. If the EXPR does not specify a path, uses the current
directory. If EXPR is omitted, the value of $_ is used.
From Perl 5.6 on, expansion is done internally, rather than using an external
script. Expansion follows the csh (and any derivatives, including tcsh and bash)
style of expansion, which translates as the following:
Files beginning with a single period are ignored unless EXPR explicitly
matches.
The [..] construct matches the characters listed, including ranges, as per
regular expressions.
373
Perl
The ~ characters matches the home directory; ~name matches the home
directory for the user name.
Syntax
Following is the simple syntax for this function:
glob EXPR
glob
Return Value
This function returns undef on error otherwise First file in the list of expanded
names in scalar context and Empty list on error otherwise List of expanded file
names in list context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
gmtime
Description
This function returns a list of values corresponding to the date and time as
specified by EXPR, or date and time returned by the time function if EXPR is
omitted, localized for the standard Greenwich mean time. The values returned
are as follows:
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);
374
Perl
All list elements are numeric, and come straight out of the C `struct tm'. $sec,
$min, and $hour are the seconds, minutes, and hours of the specified time.
$mday is the day of the month, and $mon is the month itself, in the range 0..11
with 0 indicating January and 11 indicating December. $year is the number of
years since 1900. That is, $year is 123 in year 2023. $wday is the day of the
week, with 0 indicating Sunday and 3 indicating Wednesday. $yday is the day of
the year, in the range 0..364 (or 0..365 in leap years). $isdst is always 0 .
Syntax
Following is the simple syntax for this function:
gmtime EXPR
gmtime
Return Value
This function returns a string of the form: Thu Sep 21 14:52:52 2000 in scalar
context and in list context the individual time component values (seconds,
minutes, hours, day of month, month, year, day of week, day of year, daylight
savings time).
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
$local_time = gmtime();
1 09:06:41 2013
375
Perl
goto
Description
This function has three forms, the first form causes the current execution point
to jump to the point referred to as LABEL. A goto in this form cannot be used to
jump into a loop or external function.you can only jump to a point within the
same scope.
The second form expects EXPR to evaluate to a recognizable LABEL. In general,
you should be able to use a normal conditional statement or function to control
the execution of a program, so its use is deprecated.
The third form substitutes a call to the named subroutine for the currently
running subroutine. The new subroutine inherits the argument stack and other
features of the original subroutine; it becomes impossible for the new subroutine
even to know that it was called by another name.
Syntax
Following is the simple syntax for this function:
goto LABEL
goto EXPR
goto &NAME
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
$count = 0;
START:
376
Perl
$count = $count + 1;
grep
Description
This function extract any elements from LIST for which EXPR is TRUE.
Syntax
Following is the simple syntax for this function:
grep EXPR, LIST
Return Value
This function returns the number of times the expression returned true in scalar
context and list of elements that matched the expression in list context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
Perl
print "@has_digit\n";
When above code is executed, it produces the following result:
1 0 20
hex
Description
This function interprets EXPR as a hexadecimal string and returns the value, or
converts $_ if EXPR is omitted.
Syntax
Following is the simple syntax for this function:
hex EXPR
hex
Return Value
This function returns numeric value equivalent to hexa in scalar context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
# same
Perl
175
import
Description
This function is an ordinary method (subroutine) defined (or inherited) by
modules that wish to export names to another module. The use function calls
the import method for the package used.
Syntax
Following is the simple syntax for this function:
import LIST
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
package Util;
use base 'Exporter';
sub foo {
print "foo!";
}
sub bar {
print "bar!";
}
package Amy;
use Util 'foo';
Perl
foo();
# works fine
bar();
# blows up
index
Description
This function returns the position of the first occurrence of SUBSTR in STR,
starting at the beginning (starting at zero), or from POSITION if specified.
Syntax
Following is the simple syntax for this function:
index STR, SUBSTR, POSITION
Return Value
This function returns -1 on failure otherwise Position of matching string (starting
at zero for the first character).
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
Perl
int
Description
This function returns the integer element of EXPR, or $_ if omitted. The int
function does not do rounding. If you need to round a value up to an integer,
you should use sprintf.
Syntax
Following is the simple syntax for this function:
int EXPR
int
Return Value
This function returns the integer part of EXPR.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
$int_val = int( 10 / 3 );
print"Integer value is $int_val\n";
When above code is executed, it produces the following result:
Integer value is 6
Integer value is -6
Integer value is 3
381
Perl
ioctl
Description
This function performs the function FUNCTION using the system function ioctl( ),
using SCALAR to set or receive information when appropriate. The available
values for FUNCTION are completely system independent. You should refer to
your ioctl.h C header file, if you have one available, for suitable values.
Syntax
Following is the simple syntax for this function:
ioctl FILEHANDLE, FUNCTION, SCALAR
Return Value
This function returns undef on failure otherwise 0 but true if the return value
from the ioctl( )is 0.
Example
Following is the example code showing its basic usage:
join
Description
This function combines the elements of LIST into a single string using the value
of EXPR to separate each element. It is effectively the opposite of split.
Note that EXPR is only interpolated between pairs of elements in LIST; it will not
be placed either before the first or after the last element in the string. To join
together strings without a separator, supply an empty string rather than undef.
Syntax
Following is the simple syntax for this function:
join EXPR, LIST
382
Perl
Return Value
This function returns the joined string.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
keys
Description
This function returns all the keys of the HASH as a list. The keys are returned in
random order but, in fact, share the same order as that used by values and
each.
Syntax
Following is the simple syntax for this function:
keys HASH
Return Value
This function returns number of keys in the hash in scalar context and list of
keys in list context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
383
Perl
4-3-2-1
kill
Description
This function sends a signal to a list of processes. Returns the number of
processes successfully signaled.
If SIGNAL is zero, no signal is sent to the process. This is a useful way to check
that a child process is alive and hasn't changed its UID. The precise list of
signals supported is entirely dependent on the system implementation:
Name
Effect
SIGABRT
SIGARLM
Alarm signal
SIGFPE
Arithmetic exception
SIGHUP
Hang up.
SIGILL
Illegal instruction
SIGINT
Interrupt
SIGKILL
Termination signal
SIGPIPE
SIGQUIT
Quit signal.
384
Perl
SIGSEGV
Segmentation fault
SIGTERM
Termination signal
SIGUSER1
Application-defined signal 1
SIGUSER2
Application-defined signal 2
Syntax
Following is the simple syntax for this function:
kill EXPR, LIST
Return Value
This function returns the number of processes successfully signaled.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
last
Description
This is not a function. The last keyword is a loop-control statement that
immediately causes the current iteration of a loop to become the last. No further
statements are executed, and the loop ends. If LABEL is specified, then it drops
out of the loop identified by LABEL instead of the currently enclosing loop.
Syntax
Following is the simple syntax for this function:
last LABEL
385
Perl
last
Return Value
This does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
$count = 0;
while( 1 ){
$count = $count + 1;
if( $count > 4 ){
print "Going to exist out of the loop\n";
last;
}else{
print "Count is $count\n";
}
}
print "Out of the loop\n";
When above code is executed, it produces the following result:
Count is 1
Count is 2
Count is 3
Count is 4
Going to exist out of the loop
Out of the loop
386
Perl
lc
Description
This function returns a lowercased version of EXPR, or $_ if EXPR is omitted.
Syntax
Following is the simple syntax for this function:
lc EXPR
lc
Return Value
This function returns a lowercased version of EXPR, or $_ if EXPR is omitted.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
lcfirst
Description
This function returns the string EXPR or $_ with the first character lowercased.
Syntax
Following is the simple syntax for this function:
387
Perl
lcfirst EXPR
lfirstc
Return Value
This function returns the string EXPR or $_ with the first character lowercased.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
length
Description
This function returns the length, in characters, of the value of EXPR, or $_ if not
specified. Use scalar context on an array or hash if you want to determine the
corresponding size.
Syntax
Following is the simple syntax for this function:
length EXPR
length
Return Value
This function returns the size of string.
388
Perl
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
length( orig_string );
print "Length of
String is : $string_len\n";
String is : 11
link
Description
This function creates a new file name, NEWFILE, linked to the file OLDFILE. The
function creates a hard link; if you want a symbolic link, use the symlink
function.
Syntax
Following is the simple syntax for this function:
link OLDFILE,NEWFILE
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage, this will create new file
using existing file:
#!/usr/bin/perl
$existing_file = "/usr/home/test1";
$new_file = "/usr/home/test2";
$retval = link $existing_file, $new_file ;
389
Perl
if( $retval == 1 ){
print"Link created successfully\n";
}else{
print"Error in creating link $!\n";
}
When above code is executed, it produces the following result:
Link created successfully
listen
Description
This function configures the network socket SOCKET for listening to incoming
network connections. Sets the incoming connection queue length to EXPR. You
might want to consider using the IO::Socket module, which provides a much
easier way of creating and listening to network sockets.
Syntax
Following is the simple syntax for this function:
listen SOCKET, EXPR
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage, this is a server example
alongwith socket implementation Perl Socket:
Perl Socket
#!/usr/bin/perl -w
# server.pl
#--------------------
use strict;
use Socket;
390
Perl
# accepting a connection
my $client_addr;
while ($client_addr = accept(NET_SOCKET, SOCKET)) {
# send them a message, close connection
print NEW_SOCKET "Smile from the server";
close NEW_SOCKET;
}
When above code is executed, it produces the following result:
local
Description
This function sets the variables in LIST to be local to the current execution block.
If more than one value is specified, you must use parentheses to define the list.
391
Perl
Note that local creates a local copy of a variable, which then goes out of scope
when the enclosing block terminates. The localized value is then used whenever
it is accessed, including any subroutines and formats used during that block.
Syntax
Following is the simple syntax for this function:
local LIST
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
local $foo;
localtime
Description
This function converts the time specified by EXPR in a list context, returning a
nine-element array with the time analyzed for the current local time zone. The
elements of the array are
# 0
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
If EXPR is omitted, uses the value returned by time.
$mday is the day of the month, and $mon is the month itself, in the range 0..11
with 0 indicating January and 11 indicating December.
392
Perl
$year is the number of years since 1900, not just the last two digits of the year.
That is, $year is 123 in year 2023. The proper way to get a complete 4-digit
year is simply: $year += 1900;
Syntax
Following is the simple syntax for this function:
localtime EXPR
Return Value
This function returns a string of the form: Thu Sep 21 14:52:52 2000 in scalar
context and the individual time component values (seconds, minutes, hours, day
of month, month, year, day of week, day of year, daylight savings time) in list
context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
use POSIX;
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
localtime(time);
$year += 1900;
print "$sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst\n";
$now_string = localtime;
print "$now_string\n";
1 14:58:19 2013
Sun Sep
1 14:58:19 2013
393
Perl
lock
Description
This function places an advisory lock on a shared variable, or referenced object
contained in THING until the lock goes out of scope.
lock() is a "weak keyword" : this means that if you've defined a function by this
name before any calls to it, that function will be called instead.
Syntax
Following is the simple syntax for this function:
lock THING
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
log
Description
This function returns the natural logarithm of EXPR, or $_ if omitted. To get the
log of another base, use basic algebra: The base-N log of a number is equal to
the natural log of that number divided by the natural log of N.
Syntax
Following is the simple syntax for this function:
log EXPR
log
394
Perl
Return Value
This function returns Floating point number in scalar context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
sub log10 {
my $n = shift;
return log($n)/log(10);
}
When above code is executed, it produces the following result:
log10(2): 0.301029995663981
log10(2): 0.477121254719662
log10(2): 0.698970004336019
lstat
Description
This function performs the same tests as the stat function on FILEHANDLE or the
file referred to by EXPR or $_
If the file is a symbolic link, it returns the information for the link, rather than
the file it points to. Otherwise, it returns the information for the file.
Syntax
Following is the simple syntax for this function:
lstat FILEHANDLE
lstat EXPR
395
Perl
lstat
Return Value
This function returns a list of 13 elements in list context, these fields are as
follows:
0 dev
1 ino
inode number
2 mode
file mode
3 nlink
4 uid
5 gid
6 rdev
7 size
8 atime
9 mtime
10 ctime
11 blksize
12 blocks
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
$filename = "/tmp/test.pl";
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
$atime,$mtime,$ctime,$blksize,$blocks)
= lstat($filename);
printf "File is %s,\n size is %s,\n perm %04o, mtime %s\n",
$filename, $size, $mode & 07777,
scalar localtime $mtime;
When above code is executed, it produces the following result:
396
Perl
m
Description
This match operator is used to match any keyword in given expression.
Parentheses after initial m can be any character and will be used to delimit the
regular expression statement.
Regular expression variables include $, which contains whatever the last
grouping match matched; $&, which contains the entire matched string; $`,
which contains everything before the matched string; and $', which contains
everything after the matched string.
Syntax
Following is the simple syntax for this function:
m//
Return Value
This function returns 0 on failure and 1 on success,
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
Perl
map
Description
This function Evaluates EXPR or BLOCK for each element of LIST. For each
iteration, $_ holds the value of the current element, which can also be assigned
to allow the value of the element to be updated.
Simply, Perl's map() function runs an expression on each element of an array,
and returns a new array with the results.
Syntax
Following is the simple syntax for this function:
map EXPR, LIST
Return Value
This function returns the total number of elements so generated in scalar
context and list of values in list context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
Perl
Andrew
mkdir
Description
This function makes a directory with the name and path EXPR using the mode
specified by MODE, which should be supplied as an octal value for clarity.
Syntax
Following is the simple syntax for this function:
mkdir EXPR,MODE
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
$dirname ="/tmp/testdir";
mkdir $dirname, 0755;
When above code is executed, it produces the following result in /tmp directory:
drwxr-xr-x
2 root
root
msgctl
Description
This function calls the system function msgctrl( ) with the arguments ID, CMD,
and ARG. You may need to include the IPC::SysV package to obtain the correct
constants.
Syntax
Following is the simple syntax for this function:
399
Perl
Return Value
This function returns 0 but true if the system function returns 0 and 1 on
success.
Example
Following is the example code showing its basic usage:
msgget
Description
This function calls the System V IPC function msgget(2). Returns the message
queue id, or the undefined value if there is an error.
Syntax
Following is the simple syntax for this function:
msgget KEY, FLAGS
Return Value
This function returns undef on error and Message queue ID on success.
Example
Following is the example code showing its basic usage:
400
Perl
msgrcv
Description
This function receives a message from the queue ID, placing the message into
the variable VAR, up to a maximum size of SIZE.
Syntax
Following is the simple syntax for this function:
msgrcv ID, VAR, SIZE, TYPE, FLAGS
Return Value
This function returns 0 on error and 1 on success.
Example
Following is the example code showing its basic usage:
msgsnd
Description
This function sends the message MSG to the message queue ID, using the
optional FLAGS.
Syntax
Following is the simple syntax for this function:
msgsnd ID, MSG, FLAGS
Return Value
This function returns 0 on error and 1 on success.
Example
401
Perl
my
Description
This function declares the variables in LIST to be lexically scoped within the
enclosing block. If more than one variable is specified, all variables must be
enclosed in parentheses.
Syntax
Following is the simple syntax for this function:
my LIST
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
sub myfunction
{
my $string = "We are the function";
print "$string\n";
mysub();
402
Perl
}
sub mysub
{
print "$string\n";
}
When above code is executed, it produces the following result:
We are the world
We are the function
We are the world
We are the world
next
Description
This is not a function, it causes the current loop iteration to skip to the next
value or next evaluation of the control statement. No further statements in the
current loop are executed. If LABEL is specified, then execution skips to the next
iteration of the loop identified by LABEL.
Syntax
Following is the simple syntax for this function:
next LABEL
next
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
@list = (1,2,3,4,5,5,3,6,7,1 );
403
Perl
no
Description
This function calls the unimport function defined in MODULE to unimport all
symbols from the current package if MODULE supports it, or only the symbols
referred to by LIST. It can be said that no is opposite of import
Syntax
Following is the simple syntax for this function:
no Module VERSION LIST
no Module VERSION
no MODULE LIST
404
Perl
no MODULE
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
oct
Description
This function converts EXPR from octal to decimal. For example, oct('0760') will
return '496'. You can use the string returned as a number because Perl will
automatically convert strings to numbers in numeric contexts. Passed parameter
should be an octal number otherwise it will produce zero as a result.
Syntax
Following is the simple syntax for this function:
oct EXPR
oct
Return Value
This function returns the decimal value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
Perl
open
Description
This function opens a file using the specified file handle. The file handle may be
an expression, the resulting value is used as the handle. If no filename is
specified a variable with the same name as the file handle used (this should be a
scalar variable with a string value referring to the file name). The special file
name '-' refers to STDIN and '>-' refers to STDOUT.
Syntax
Following is the simple syntax for this function:
open FILEHANDLE, EXPR, LIST
open FILEHANDLE
Return Value
This function returns o on failure and 1 on success.
Example
Following is the syntax to open file.txt in read-only mode. Here less than < sign
indicates that file has to be opend in read-only mode
open(DATA, "<file.txt");
Here DATA is the file handle which will be used to read the file. Here is the
example which will open a file and will print its content over the screen.
#!/usr/bin/perl
open(DATA, "<file.txt");
406
Perl
while(<DATA>)
{
print "$_";
}
Following is the syntax to open file.txt in writing mode. Here less than > sign
indicates that file has to be opend in writing mode
open(DATA, ">file.txt");
This example actually truncates (empties) the file before opening it for writing,
which may not be the desired effect. If you want to open a file for reading and
writing, you can put a plus sign before the > or < characters.
For example, to open a file for updating without truncating it:
open(DATA, "+<file.txt");
To truncate the file first:
open DATA, "+>file.txt" or die "Couldn't open file file.txt, $!";
You can open a file in append mode. In this mode writing point will be set to the
end of the file
open(DATA,">>file.txt") || die "Couldn't open file file.txt, $!";
A double >> opens the file for appending, placing the file pointer at the end, so
that you can immediately start appending information. However, you can.t read
from it unless you also place a plus sign in front of it:
open(DATA,"+>>file.txt") || die "Couldn't open file file.txt, $!";
Following is the table which gives the possible values of different modes.
Entities
Definition
< or r
> or w
>> or a
+< or r+
+> or w+
Perl
opendir
Description
This function opens the directory EXPR, associating it with DIRHANDLE for
processing, using the readdir function.
Syntax
Following is the simple syntax for this function:
opendir DIRHANDLE, EXPR
Return Value
This function returns true if successful.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
$dirname = "/tmp";
408
Perl
ord
Description
This function returns the ASCII numeric value of the character specified by
EXPR, or $_ if omitted. For example, ord('A') returns a value of 65.
Syntax
Following is the simple syntax for this function:
ord EXPR
ord
Return Value
This function returns Integer.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
our
Description
This function defines the variables specified in LIST as being global within the
enclosing block, file, or eval statement. It is effectively the opposite of my.it
declares a variable to be global within the entire scope, rather than creating a
new private variable of the same name. All other options are identical to my;
An our declaration declares a global variable that will be visible across its entire
lexical scope, even across package boundaries. The package in which the
variable is entered is determined at the point of the declaration, not at the point
of use. If more than one value is listed, the list must be placed in parentheses.
409
Perl
Syntax
Following is the simple syntax for this function:
our EXPR
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
sub myfunction
{
our $string = "We are the function";
print "$string\n";
}
When above code is executed, it produces the following result:
We are the world
We are the function
We are the function
410
Perl
pack
Description
This function evaluates the expressions in LIST and packs them into a binary
structure specified by EXPR. The format is specified using the characters shown
in Table below:
Each character may be optionally followed by a number, which specifies a repeat
count for the type of value being packed.that is nibbles, chars, or even bits,
according to the format. A value of * repeats for as many values remain in LIST.
Values can be unpacked with the unpack function.
For example, a5 indicates that five letters are expected. b32 indicates that 32
bits are expected. h8 indicates that 8 nybbles ( or 4 bytes) are expected. P10
indicates that the structure is 10 bytes long.
Syntax
Following is the simple syntax for this function:
pack EXPR, LIST
Return Value
This function returns a packed version of the data in LIST using TEMPLATE
to determine how it is coded.
Description
Perl
A signed integer
An unsigned integer
A pointer to a string
A null byte
Perl
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
413
Perl
package
Description
This function Changes the name of the current symbol table to NAME. The scope
of the package name is until the end of the enclosing block. If NAME is omitted,
there is no current package, and all function and variables names must be
declared with their fully qualified names.
Syntax
Following is the simple syntax for this function:
package NAME
package
Return Value
This function does not return any value.
Example
To understand package keyword check Perl Modules session.
Following is the example code showing its basic usage:
pipe
Description
This function opens a pair of connected communications pipes: READHANDLE for
reading and WRITEHANDLE for writing. YOu may need to set $| to flush your
WRITEHANDLE after each command.
Syntax
Following is the simple syntax for this function:
414
Perl
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
use IO::Handle;
pipe(PARENTREAD, PARENTWRITE);
pipe(CHILDREAD, CHILDWRITE);
PARENTWRITE->autoflush(1);
CHILDWRITE->autoflush(1);
Perl
close CHILDREAD;
close PARENTWRITE;
exit;
}
It will produce following results: You can see that the calculation is sent to
CHILDWRITE, which is then read by the child from CHILDREAD. The result is
then calculated and sent back to the parent via PARENTWRITE, where the parent
reads the result from PARENTREAD.
Got 34+56;
Got a value of 90 from child
pop
Description
This function returns the last element of ARRAY, removing the value from the
array. Note that ARRAY must explicitly be an array, not a list.
If ARRAY is omitted, it pops the last value from @ARGV in the main program or
when called within eval STRING, or the BEGIN, CHECK, INIT, or END blocks.
Otherwise, it attempts to pop information from the @_ array within a
subroutine. It is the opposite of push, which when used in combination, allows
you to implement "stacks".
Note that after applying pop the array will be shortened by one element.
Syntax
Following is the simple syntax for this function:
pop ARRAY
pop
Return Value
This function returns undef if list is empty else last element from the array.
Example
Following is the example code showing its basic usage:
416
Perl
#!/usr/bin/perl -w
@a = (1, 2, 3, 4);
print("pop() ", pop(@a), "
leaves
",@a, "\n");
leaves 123
pos
Description
This function is used to find the offset or position of the last matched substring.
If SCALAR is specified, it will return the offset of the last match on that scalar
variable.
You can also assign a value to this function (for example, pos($foo) = 20;) in
order to change the starting point of the next match operation.
Offset is counter starting from zeroth position.
Syntax
Following is the simple syntax for this function:
pos EXPR
pos
Return Value
This function returns Integer in Scalar context and then positions of all the
matches within the regular expression in List context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
Perl
print
Description
This function prints the values of the expressions in LIST to the current default
output filehandle, or to the one specified by FILEHANDLE.
If set, the $\ variable will be added to the end of the LIST.
If LIST is empty, the value in $_ is printed instead.
print accepts a list of values and every element of the list will be interpreted as
an expression.
Syntax
Following is the simple syntax for this function:
print FILEHANDLE LIST
print LIST
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
Perl
printf
Description
This function prints the value of LIST interpreted via the format specified by
FORMAT to the current output filehandle, or to the one specified by FILEHANDLE.
Effectively equivalent to print FILEHANDLE sprintf(FORMAT, LIST)
You can use print in place of printf if you do not require a specific output format.
Following is the list of accepted formatting conversions.
Format
Result
%%
A percent sign
%c
%s
A string
%d
%u
%o
%x
%X
419
Perl
%e
%E
%f
%g
%G
A floating point number (as %g, but using .E. in place of .e.
when appropriate)
%p
%n
Perl also supports flags that optionally adjust the output format. These are
specified between the % and conversion letter. They are shown in the following
table:
Flag
Result
space
number
.number
420
Perl
Syntax
Following is the simple syntax for this function:
printf FILEHANDLE FORMAT, LIST
Return Value
This function
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
printf "%d\n", 3.1415126;
printf "The cost is \$%6.2f\n",499;
printf "Perl's version is v%vd\n",%^V;
printf "%04d\n", 20;
When above code is executed, it produces the following result:
3
The cost is $499.00
Perl's version is v
0020
421
Perl
prototype
Description
This function returns a string containing the prototype of the function or
reference specified by EXPR, or undef if the function has no prototype.
You can also use this to check the availability of built-in functions.
Syntax
Following is the simple syntax for this function:
prototype EXPR
Return Value
This function returns undef if no function prototype else returns string containing
the prototype of the function or reference specified by EXPR.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
sub myprint($$){
print "This is test\n";
}
When above code is executed, it produces the following result:
myprint prototype is $$
push
Description
This function pushes the values in LIST onto the end of the list ARRAY. Used
with pop to implement stacks.
422
Perl
Syntax
Following is the simple syntax for this function:
push ARRAY, LIST
Return Value
This function returns number of elements in new array.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
$, = ",";
@array = ( 1, 2 );
print "Before pushing elements
@array \n";
@array \n";
1 2
1 2 3 4 5
q
Description
This function can be used instead of single quotes. This is not really a function,
more like an operator, but you'll probably look here if you see it in another
programmer's program without remembering what it is. You can actually use
any set of delimiters, not just the parentheses.
Syntax
Following is the simple syntax for this function:
q ( string )
423
Perl
Return Value
This function retuns a single-quoted string.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
$var = 10;
print(q(This is a single quoted string without interpolation, $var));
When above code is executed, it produces the following result:
qq
Description
This function can be used instead of double quotes. This is not really a function,
more like an operator, but you'll probably look here if you see it in another
programmer's program without remembering what it is. You can actually use
any set of delimiters, not just the parentheses.
Syntax
Following is the simple syntax for this function:
qq ( string )
Return Value
This function returns a double-quoted string.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
$var = 10;
print(qq(This is a single quoted string with interpolation, $var));
424
Perl
qr
Description
This function quotes its STRING as a regular expression. STRING is interpolated
the same way as PATTERN in m/PATTERN/
Syntax
Following is the simple syntax for this function:
qr EXPR
Return Value
This function returns a Perl value which may be used instead of the
corresponding /STRING/ expression.
Example
Following is the example code showing its basic usage:
$rex = qr/my.STRING/is;
s/$rex/foo/;
is is equivalent to
s/my.STRING/foo/is;
When above code is executed, it produces the following result:
$re = qr/$pattern/;
$string =~ /foo${re}bar/;
$string =~ $re;
# or used standalone
$string =~ /$re/;
# or this way
425
Perl
quotemeta
Description
This function escapes all meta-characters
quotemeta("AB*..C") returns "'AB\*\.\.C".
in
EXPR.
For
example,
Syntax
Following is the simple syntax for this function:
quotemeta EXPR
Return Value
This function returns a string with all meta-characters escaped.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
print quotemeta("AB*\n[.]*");
When above code is executed, it produces the following result:
AB\*\
\[\.\]\*
qw
Description
This function is a quick way to specify a lot of little single-quoted words. For
example, qw(foo bar baz) is equivalent to ('foo', 'bar', 'baz'). Some
programmers feel that using qw make Perl scripts easier to read. You can
actually use any set of delimiters, not just the parentheses.
Simply you can use qw() to prepare an array as shown in the example below.
Syntax
Following is the simple syntax for this function:
426
Perl
qw EXPR
Return Value
This function return a list consisting of the element of LIST evaluated as if they
were single-quoted.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
qx
Description
This function is a alternative to using back-quotes to execute system commands.
For example, qx(ls -l) will execute the UNIX ls command using the -l commandline option. You can actually use any set of delimiters, not just the parentheses.
Syntax
Following is the simple syntax for this function:
427
Perl
qx EXPR
Return Value
This function returns the value from the executed system command.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
print "@output\n";
When above code is executed, it produces the following result:
176
/tmp
rand
Description
This function returns a random fractional number between 0 and the positive
number EXPR, or 1 if not specified. Automatically calls srand to seed the random
number generator unless it has already been called.
Syntax
Following is the simple syntax for this function:
rand EXPR
rand
Return Value
This function returns a Floating point number.
428
Perl
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
read
Description
This function reads, or attempts to read, LENGTH number of bytes from the file
associated with FILEHANDLE into BUFFER. If an offset is specified, the bytes that
are read are placed into the buffer starting at the specified offset.
Syntax
Following is the simple syntax for this function:
read FILEHANDLE, SCALAR, LENGTH, OFFSET
Return Value
This function the number of bytes read or the undefined value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
my($buffer) = "";
open(FILE, "/etc/services") or
die("Error reading file, stopped");
while(read(FILE, $buffer, 100) )
429
Perl
{
print("$buffer\n");
}
close(FILE);
When above code is executed, it produces the following result:
kerberos_master 751/udp
# Kerberos authentication
kerberos_master 751/tcp
# Kerberos authentication
passwd_server
752/udp
readdir
Description
This function returns the next directory entry from the directory associated with
DIRHANDLE in a scalar context. In a list context, returns all of the remaining
directory entries in DIRHANDLE.
Syntax
Following is the simple syntax for this function:
readdir DIRHANDLE
Return Value
This function returns the next directory entry from the directory associated with
DIRHANDLE in a scalar context. In a list context, returns all of the remaining
directory entries in DIRHANDLE.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
$dirname = "/tmp";
Perl
print("$filename\n");
}
closedir(DIR);
When above code is executed, it produces the following result:
.
..
testdir
readline
Description
This function reads a line from the filehandle referred to by EXPR, returning the
result. If you want to use a FILEHANDLE directly, it must be passed as a
typeglob.
Simply readline function is equvivalent to <>.
Syntax
Following is the simple syntax for this function:
readline EXPR
Return Value
This function returns only one line in a scalar context and in a list context, a list
of line up to end-of-file is returned
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
my($buffer) = "";
open(FILE, "/etc/services") or
die("Error reading file, stopped");
$buffer = <FILE>;
431
Perl
print("$buffer");
close(FILE);
When above code is executed, it produces the following result:
# /etc/services:
# $Id: services,v 1.33 2003/03/14 16:41:47 notting Exp $
readlink
Description
This function returns the pathname of the file pointed to by the link EXPR, or $_
if EXPR is not specified
Syntax
Following is the simple syntax for this function:
readlink EXPR
readlink
Return Value
This function returns undef on error otherwise pathname of the file.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
readlink "/tmp/test";
432
Perl
readpipe
Description
This function executes EXPR as a command. The output is then returned as a
multiline string in scalar text, or with the line returned as individual elements in
a list context.
Syntax
Following is the simple syntax for this function:
readpipe EXPR
Return Value
This function returns String in Scalar Context and returns List in List Context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
print "@result";
When above code is executed, it produces the following result. This will give
whole content in /tmp directory:
drwxr-xr-x
2 root
root
recv
Description
This function receives a message on SOCKET attempting to read LENGTH bytes,
placing the data read into variable SCALAR.The FLAGS argument takes the same
433
Perl
values as the recvfrom( ) system function, on which the function is based. When
communicating with sockets, this provides a more reliable method of reading
fixed-length data than the sysread function or the line-based operator <FH>.
Syntax
Following is the simple syntax for this function:
recv SOCKET, SCALAR, LEN, FLAGS
Return Value
This function returns in Scalar Context: undef on error or Number of bytes read.
Example
Following is the example code showing its basic usage:
redo
Description
This function restarts the current loop without forcing the control statement to
be evaluated. No further statements in the block are executed. A continue block,
if present, will not be executed. If LABEL is specified, execution restarts at the
start of the loop identified by LABEL.
Syntax
Following is the simple syntax for this function:
redo LABEL
redo
Return Value
This function does not return any value.
434
Perl
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
$c = 1;
$d = 4;
LABEL:
{
$c++;
$e = 5;
redo LABEL if ($c < 3);
$f = 6;
last LABEL if ($e > 3);
$g = 7;
}
$h = 8;
print ("$c $d $e $f $g $h\n");
When above code is executed, it produces the following result:
3 4 5 6 7
ref
Description
This function returns a true value if EXPR, or $_ if EXPR is not supplied, is a
reference. The actual value returned also defines the type of entity the reference
refers to.
The built-in types are:
REF
SCALAR
ARRAY
HASH
CODE
435
Perl
GLOB
LVALUE
IO::Handle
If a variable was blessed with the bless() function, then the new data type will
be returned. The new data type will normally be a class name.
Syntax
Following is the simple syntax for this function:
ref EXPR
ref
Return Value
This function returns empty string if not a reference and string if a reference in
Scalar Context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
$foobar = { };
bless($foobar, 'ATMPCLASS');
print "ref() \$foobar is now in class ", ref($foobar), "\n";
When above code is executed, it produces the following result:
ref() $foobar is now in class ATMPCLASS
rename
Description
This function renames the file with OLDNAME to NEWNAME. Uses the system
function rename( ), and so it will not rename files across file systems or
volumes. If you want to copy or move a file, use the copy or move command
supplied in the File::Copy module.
436
Perl
Syntax
Following is the simple syntax for this function:
rename OLDNAME, NEWNAME
Return Value
This function returns 0 on failure and 1 on success.
Example
First create test file in /tmp directory and then use following code to change file
name.
#!/usr/bin/perl -w
require
Description
This function then it demands that the script requires the specified version of
Perl in order to continue if EXPR is numeric. If EXPR or $_ are not numeric, it
assumes that the name is the name of a library file to be included. You cannot
include the same file with this function twice. The included file must return a
true value as the last statement.
This differs from use in that included files effectively become additional text for
the current script. Functions, variables, and other objects are not imported into
the current name space, so if the specified file includes a package definition,
then objects will require fully qualified names.
The specified module is searched for in the directories defined in @INC, looking
for a file with the specified name and an extension of .pm.
Syntax
Following is the simple syntax for this function:
require EXPR
437
Perl
require
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
..............
When above code is executed, it produces the following result:
reset
Description
This function resets (clears) all package variables starting with the letter range
specified by EXPR. Generally only used within a continue block or at the end of a
loop. If omitted, resets ?PATTERN? matches.
Variables that have been declared using the my() function will not be reset.
Using reset() can reset system variables you may not want to alter-like the
ARGV and ENV variables.
Syntax
Following is the simple syntax for this function:
reset EXPR
438
Perl
reset
Return Value
This function returns 1.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
my $var = 10;
$van = 5;
return
Description
This function returns EXPR at the end of a subroutine, block, or do function.
EXPR may be a scalar, array, or hash value; context will be selected at execution
time. If no EXPR is given, returns an empty list in list context, undef in scalar
context, or nothing in a void context.
Syntax
Following is the simple syntax for this function:
return EXPR
439
Perl
return
Return Value
This function returns in Scalar Context: List, which may be interpreted as scalar,
list, or void context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
$retval = Sum(5,10);
print ("Return value is $retval\n" );
@retval = Sum(5,10);
print ("Return value is @retval\n" );
sub Sum($$){
my($a, $b ) = @_;
my $c = $a + $b;
reverse
Description
This function returns the elements of LIST in reverse order in a list context. In a
scalar context, returns a concatenated string of the values of LIST, with all bytes
in opposite order.
440
Perl
Syntax
Following is the simple syntax for this function:
reverse LIST
Return Value
This function returns String in Scalar Context and List in List Context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
@array = (2,3,4,5,6,7);
print "Reversed Value is ", reverse(@array), "\n";
$string = "Hello World";
print "Reversed Value is ", scalar reverse("$string"), "\n";
When above code is executed, it produces the following result:
Reversed Value is 765432
Reversed Value is dlroW olleH
rewinddir
Description
This function Resets the current position within the directory specified by
DIRHANDLE to the beginning of the directory.
Syntax
Following is the simple syntax for this function:
rewinddir DIRHANDLE
Return Value
This function returns 0 on failure and 1 on success.
Example
441
Perl
closedir(DIR);
When above code is executed, it produces the following result(in /tmp
directory):
1st Time:
.
..
testdir
The last file has already been read!
2nd Time:
442
Perl
.
..
testdir
rindex
Description
This function operates similar to index, except it returns the position of the last
occurrence of SUBSTR in STR. If POSITION is specified, returns the last
occurrence at or before that position.
Syntax
Following is the simple syntax for this function:
rindex STR, SUBSTR, POSITION
Return Value
This function returns undef on failure otherwise position of last occurence.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
Perl
rmdir
Description
This function deletes the directory specified by EXPR, or $_ if omitted. Only
deletes the directory if the directory is empty.
Syntax
Following is the simple syntax for this function:
rmdir EXPR
rmdir
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage, create one directory
testdir inside /tmp:
#!/usr/bin/perl -w
444
Perl
s
Description
This is not a function. This is the regular expression-substitution operator. Based
on the regular expression specified in PATTERN, data is replaced by REPLACE.
Like m//, the delimiters are defined by the first character following s.
Syntax
Following is the simple syntax for this function:
s/PATTERN/REPLACE/
Return Value
This function returns 0 on failure and number of substitutions made on success.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
print "$string\n";
When above code is executed, it produces the following result:
This is Best
scalar
Description
This function forces the evaluation of EXPR to be in scalar context, even if it
would normally work in list context.
445
Perl
Syntax
Following is the simple syntax for this function:
scalar EXPR
Return Value
This function returns Scalar.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
@a = (1,2,3,4);
@b = (10,20,30,40);
@c = ( @a, @b );
print "1 - Final Array is @c\n";
@c = ( scalar(@a), scalar(@b) );
print "2 - Final Array is @c\n";
When above code is executed, it produces the following result:
1 - Final Array is 1 2 3 4 10 20 30 40
2 - Final Array is 4 4
seek
Description
This function moves to a specified position in a file. You can move relative to the
beginning of the file (WHENCE = 0), the current position (WHENCE = 1), or the
end of the file (WHENCE = 2). This function is mainly used with fixed length
records to randomly access specific records of the file.
For WHENCE you may use the constants SEEK_SET , SEEK_CUR , and
SEEK_END (start of the file, current position, end of the file) from the Fcntl
module.
446
Perl
Syntax
Following is the simple syntax for this function:
seek FILEHANDLE,POSITION,WHENCE
Return Value
This function
Example
Following is the example code showing its basic usage:
seekdir
Description
This function sets the current position within DIRHANDLE to POS. The value of
POS must be a value previously returned by telldir.
seekdir() function is similar to Unix seekdir() system call.
Syntax
Following is the simple syntax for this function:
seekdir DIRHANDLE, POS
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage, create one directory
testdir inside /tmp:
#!/usr/bin/perl -w
447
Perl
opendir(DIR, "/tmp");
$dir = readdir(DIR);
print("Position after one read : ", telldir(DIR), "\n");
print "$dir\n";
seekdir(DIR,0);
$dir = readdir(DIR);
print "$dir\n";
print("Position after second read : " , telldir(DIR), "\n");
closedir(DIR);
When above code is executed, it produces the following result:
Position without read : 0
Position after one read : 1220443271
test.txt
test.txt
Position after second read : 1220443271
select
Description
This function sets the default filehandle for output to FILEHANDLE, setting the
filehandle used by functions such as print and write if no filehandle is specified.
If FILEHANDLE is not specified, then it returns the name of the current default
filehandle.
select (RBITS, WBITS, EBITS, TIMEOUT ) calls the system function select( )
using the bits specified. The select function sets the controls for handling nonblocking I/O requests. Returns the number of filehandles awaiting I/O in scalar
context, or the number of waiting filehandles and the time remaining in a list
context
448
Perl
Syntax
Following is the simple syntax for this function:
select FILEHANDLE
select
Return Value
TRhis function returns the previous default filehandle if FILEHANDLE specified
and Current default filehandle if FILEHANDLE is not specified.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
open(FILE,">/tmp/t.out");
$oldHandle = select(FILE);
print("This is sent to /tmp/t.out.\n");
select($oldHandle);
print("This is sent to STDOUT.\n");
When above code is executed, it produces the following result:
This is sent to STDOUT
semctl
Description
This function controls a System V semaphore. You will need to import the
IPC:SysV module to get the correct definitions for CMD. The function calls the
system semctl( ) function.
Syntax
Following is the simple syntax for this function:
449
Perl
Return Value
This function returns undef on failure and 0 but true on success.
Example
Following is the example code showing its basic usage, creating a semaphore
and incrementing its value:
#!/usr/bin/perl -w
use IPC::SysV;
$key = 1066;
$| = 1;
$num = 0;
$flag = 0;
= 0;
Perl
$op = 2;
$operation = pack( "s*", $num, $op, $flags );
# add 2 to the semaphore ( now 2 )
semop( $id, $operation ) or die "Can't semop $! ";
}
semctl (
$id, 0, &IPC_RMID, 0 );
Run the above program in background using $left.pl& and write following
another program. Here Left sets the semaphore to 2 and Right prints Right and
resets the semaphore to 0. This continues until Left finishes its loop after which
it destroys the semaphore with semctl()
#!/usr/bin/perl -w
$key = 1066;
$| = 1;
$num = 0;
$flags = 0;
foreach( 1..5){
$op = -1;
$operation =
0)
Perl
}
When above code is executed, it produces the following result:
Right....
Left....
Right....
Left....
Right....
Left....
Right....
Left....
Right....
Left....
semget
Description
This function returns the semaphore ID associated with KEY, using the system
function semget( ) ie. Finds the semaphore associated with KEY.
Syntax
Following is the simple syntax for this function:
semget KEY, NSEMS, FLAGS
Return Value
This function returns undef on failure and 0 but true on success.
Example
Following is the example code showing its basic usage, creating a semaphore
and incrementing its value:
#!/usr/bin/perl -w
Perl
use IPC::SysV;
$key = 1066;
$| = 1;
$num = 0;
$flag = 0;
= 0;
$id, 0, &IPC_RMID, 0 );
Run the above program in background using $left.pl& and write following
another program. Here Left sets the semaphore to 2 and Right prints Right and
resets the semaphore to 0. This continues until Left finishes its loop after which
it destroys the semaphore with semctl()
#!/usr/bin/perl -w
453
Perl
$key = 1066;
$| = 1;
$num = 0;
$flags = 0;
foreach( 1..5){
$op = -1;
$operation =
0)
Perl
Right....
Left....
semop
Description
This function performs the semaphore operations defined by OPSTRING on the
semaphore ID associated with KEY. OPSTRING should be a packed array of
semop structures, and each structure can be generated with.
Syntax
Following is the simple syntax for this function:
semop KEY, OPSTRING
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage, creating a semaphore
and incrementing its value:
#!/usr/bin/perl -w
use IPC::SysV;
$key = 1066;
$| = 1;
455
Perl
$num = 0;
$flag = 0;
= 0;
$id, 0, &IPC_RMID, 0 );
Run the above program in background using $left.pl& and write following
another program. Here Left sets the semaphore to 2 and Right prints Right and
resets the semaphore to 0. This continues until Left finishes its loop after which
it destroys the semaphore with semctl()
#!/usr/bin/perl -w
$key = 1066;
$| = 1;
$num = 0;
$flags = 0;
Perl
foreach( 1..5){
$op = -1;
$operation =
0)
send
Description
This function sends a message on SOCKET (the opposite of recv). If the socket is
unconnected, you must supply a destination to communicate to with the TO
parameter. In this case, the sendto system function is used in place of the
system send function.
457
Perl
The FLAGS parameter is formed from the bitwise or of 0 and one or more of the
MSG_OOB and MSG_DONTROUTE options. MSG_OOB allows you to send out-ofband data on sockets that support this notion.
The underlying protocol must also support out-of-band data. Only
SOCK_STREAM sockets created in the AF_INET address family support out-ofband data. The MSG_DONTROUTE option is turned on for the duration of the
operation. Only diagnostic or routing programs use it.
Syntax
Following is the simple syntax for this function:
send SOCKET, MSG, FLAGS, TO
Return Value
This function returns undef on failure else Integer, number of bytes sent.
Example
Following is the example code showing its basic usage:
setgrent
Description
This function Sets (or resets) the enumeration to the beginning of the set of
group entries. This function should be called before the first call to getgrent.
Syntax
Following is the simple syntax for this function:
setgrent
458
Perl
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
= $name\n";
print "Password
print "GID
= $passwd\n";
= $gid\n";
print "Members
= $members\n";
setgrent();
= $name\n";
print "Password
print "GID
= $passwd\n";
= $gid\n";
print "Members
= $members\n";
endpwent;
}
When above code is executed, it produces the following result:
Name
= root
Password
GID
= 0
Members
Name
= x
= root
= bin
459
Perl
Password
GID
= 1
Members
Name
= x
= daemon
Password
GID
= 2
Members
Name
= x
= sys
Password
GID
= 3
Members
Name
= x
= adm
Password
GID
= x
= 4
Members
.
.
.
Name
= kvm
Password
GID
= 36
Members
Name
= webgrp
Password
GID
= x
= 501
Members
Name
= com
Password
GID
= x
= 107
Members
Name
= qemu
= qemu
Password
GID
= x
= x
= 502
460
Perl
Members
Name
= railo
Password
GID
= com
= x
= 495
Members
sethostent
Description
This function should be called before the first call to gethostent. The STAYOPEN
argument is optional and unused on most systems.
As gethostent() retriews the information for the next line in the host database,
then sethostent sets (or resets) the enumeration to the beginning of the set of
host entries.
Syntax
Following is the simple syntax for this function:
sethostent STAYOPEN
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
= $name\n";
print "Aliases
= $aliases\n";
= $addrtype\n";
= $length\n";
= @addrs\n";
}
461
Perl
sethostent(1);
= $name\n";
print "Aliases
= $aliases\n";
= $addrtype\n";
= $length\n";
= @addrs\n";
endhostent();
= ip-50-62-147-141.ip.secureserver.net
= 2
= 4
=
= ip-50-62-147-141.ip.secureserver.net
= 2
= 4
=
setnetent
Description
This function should be called before the first call to getnetent. The STAYOPEN
argument is optional and unused on most systems. As getnetent() retriews the
information fro the next line in the network database, then setnetent sets (or
resets) the enumeration to the beginning of the set of host entries.
462
Perl
Syntax
Following is the simple syntax for this function:
setnetent STAYOPEN
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
use Socket;
= getnetent() ){
= getnetent() ){
endnetent();
Perl
Name = default
Aliases =
Addrtype = 2
Net = 0
Name = loopback
Aliases =
Addrtype = 2
Net = 2130706432
Name = link-local
Aliases =
Addrtype = 2
Net = 2851995648
Name = default
Aliases =
Addrtype = 2
Net = 0
Name = loopback
Aliases =
Addrtype = 2
Net = 2130706432
Name = link-local
Aliases =
Addrtype = 2
Net = 2851995648
setpgrp
Description
This function sets the current process group for the process PID. You can use a
value of 0 for PID to change the process group of the current process. If both
arguments are omitted, defaults to values of 0. Causes a fatal error if the
system does not support the function.
464
Perl
Syntax
Following is the simple syntax for this function:
setpgrp PID, PGRP
Return Value
This function returns undef on failure and new parent process ID.
Example
Following is the example code showing its basic usage:
setpriority
Description
This function sets the priority for a process (PRIO_PROCESS), process group
(PRIO_PGRP), or user (PRIO_USER). The argument WHICH specifies what entity
to set the priority for, and WHO is the process ID or user ID to set. A value of 0
for WHO defines the current process, process group, or user. Produces a fatal
error on systems that don.t support the system setpriority( ) function.
The priority is a number representing the level of priority (normally in the range
120 to 20) where the lower the priority the more favorable the scheduling of the
process by the operating system.
Syntax
Following is the simple syntax for this function:
setpriority WHICH, WHO, PRIORITY
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
465
Perl
#!/usr/bin/perl
setprotoent
Description
This function should be called before the first call to getprotoent. The STAYOPEN
argument is optional and unused on most systems. As getprotoent() retriews the
information for the next line in the protocol database, then setprotoent sets (or
resets) the enumeration to the beginning of the set of host entries.
Syntax
Following is the simple syntax for this function:
setprotoent STAYOPEN
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
466
Perl
Perl
setpwent
Description
This function Sets (or resets) the enumeration to the beginning of the set of
password entries. This function should be called before the first call to getpwent.
Syntax
Following is the simple syntax for this function:
setpwent
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
468
Perl
Perl
UID = 0
GID = 0
Quota =
Comment =
Gcos = root
HOME DIR = /root
Shell = /bin/bash
Name = bin
Password = x
UID = 1
GID = 1
Quota =
Comment =
Gcos = bin
HOME DIR = /bin
Shell = /sbin/nologin
Name = daemon
Password = x
UID = 2
GID = 2
Quota =
Comment =
Gcos = daemon
HOME DIR = /sbin
Shell = /sbin/nologin
.
.
.
Name = qemu
Password = x
UID = 107
GID = 107
Quota =
470
Perl
Comment =
Gcos = qemu user
HOME DIR = /
Shell = /sbin/nologin
Name = com
Password = x
UID = 501
GID = 501
Quota =
Comment =
Gcos =
HOME DIR = /home/com
Shell = /bin/bash
Name = railo
Password = x
UID = 497
GID = 495
Quota =
Comment =
Gcos =
HOME DIR = /opt/railo
Shell = /bin/false
setservent
Description
This function should be called before the first call to getservent. The STAYOPEN
argument is optional and unused on most systems. As getservent() retriews the
information for the next line in the services database, then setservent sets (or
resets) the enumeration to the beginning of the set of host entries.
Syntax
Following is the simple syntax for this function:
471
Perl
setservent STAYOPEN
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
setservent();
endservent();
Perl
setsockopt
Description
This function Sets the socket option OPTNAME with a value of OPTVAL on
SOCKET at the specified LEVEL. You will need to import the Socket module for
the valid values for OPTNAME shown below in Tabl
Syntax
Following is the simple syntax for this function:
setsockopt SOCKET, LEVEL, OPTNAME, OPTVAL
Return Value
This function returns undef on failure and 1 on success.
OPTNAME
Description
SO_DEBUG
SO_REUSEADDR
SO_KEEPALIVE
SO_DONTROUTE
SO_OOBINLINE
SO_ERROR
Example
Following is the example code showing its basic usage:
473
Perl
shift
Description
This function returns the first value in an array, deleting it and shifting the
elements of the array list to the left by one. If ARRAY is not specified, shifts the
@_ array within a subroutine, or @ARGV otherwise. shift is essentially identical
to pop, except values are taken from the start of the array instead of the end.
Syntax
Following is the simple syntax for this function:
shift ( [ARRAY] )
shift
Return Value
This function returns undef if the array is empty else returns first element in
array.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
@array = (1..5);
while ($element = shift(@array)) {
print("$element - ");
}
print("The End\n");
When above code is executed, it produces the following result:
1 - 2 - 3 - 4 - 5 - The End
474
Perl
shmctl
Description
This function controls the shared memory segment referred to by ID, using CMD
with ARG. You will need to import the IPC::SysV module to get the command
tokens defined below in Table.
Command
Description
IPC_STAT
IPC_SET
IPC_RMID
SHM_LOCK
SHM_UNLOCK
Syntax
Following is the simple syntax for this function:
shmctl ID, CMD, ARG
Return Value
This function returns undef on failure and 0 but true if the return value from the
shmctl( ) is 0.
475
Perl
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
writer.pl
use IPC::SysV;
$key
= 12345;
$size = 80;
$message = "Pennyfarthingale.";
sleep 20;
# Delete it;
Perl
$key = 12345;
$size = 80;
print $var;
Now First run writer.pl program in background and then reader.pl then it will
produces the following result.
$perl writer.pl&
$perl reader.pl
Pennyfrathingale
shmget
Description
This function returns the shared memory segment ID for the segment matching
KEY. A new shared memory segment is created of at least SIZE bytes, providing
that either KEY does not already have a segment associated with it or that KEY
is equal to the constant IPC_PRIVATE.
Syntax
Following is the simple syntax for this function:
shmget KEY, SIZE, FLAGS
shmget KEY
477
Perl
Return Value
This function returns undef on failure and Shared memory ID on success.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
use IPC::SysV;
$key
= 12345;
$size = 80;
$message = "Pennyfarthingale.";
sleep 20;
# Delete it;
Perl
$key = 12345;
$size = 80;
print $var;
Now First run writer.pl program in background and then reader.pl then it will
produces the following result.
$perl writer.pl&
$perl reader.pl
Pennyfrathingale
shmread
Description
This function reads the shared memory segment ID into the scalar VAR at
position POS for up to SIZE bytes.
Syntax
Following is the simple syntax for this function:
shmread ID, VAR, POS, SIZE
479
Perl
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
use IPC::SysV;
$key
= 12345;
$size = 80;
$message = "Pennyfarthingale.";
sleep 20;
# Delete it;
Perl
$key = 12345;
$size = 80;
print $var;
Now First run writer.pl program in background and then reader.pl then it will
produces the following result.
$perl writer.pl&
$perl reader.pl
Pennyfrathingale
shmwrite
Description
This function writes STRING from the position POS for SIZE bytes into the
shared memory segment specified by ID. The SIZE is greater than the length of
STRING. shmwrite appends null bytes to fill out to SIZE bytes.
Syntax
Following is the simple syntax for this function:
shmwrite ID, STRING, POS, SIZE
481
Perl
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
writer.pl
use IPC::SysV;
$key
= 12345;
$size = 80;
$message = "Pennyfarthingale.";
sleep 20;
# Delete it;
Perl
#!/usr/bin/perl
$key = 12345;
$size = 80;
print $var;
Now First run writer.pl program in background and then reader.pl then it will
produces the following result.
$perl writer.pl&
$perl reader.pl
Pennyfrathingale
shutdown
Description
This function disables a socket connection according to the value of HOW. The
valid values for HOW are identical to the system call of the same name. A value
of 0 indicates that you have stopped reading information from the socket.
A value of 1 indicates that you.ve stopped writing to the socket. A value of 2
indicates that you have stopped using the socket altogether.
Syntax
Following is the simple syntax for this function:
shutdown SOCKET, HOW
483
Perl
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage:
sin
Description
This function returns the sine of EXPR, or $_ if not specified. This function
always returns a floating point.
Syntax
Following is the simple syntax for this function:
sin EXPR
sin
Return Value
This function returns the Floating Point sin value of EXPR
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
$temp = sin(4);
Perl
sleep
Description
This function Pauses the script for EXPR seconds, or forever if EXPR is not
specified. Returns the number of seconds actually slept. Can be interrupted by a
signal handler, but you should avoid using sleep with alarm, since many systems
use alarm for the sleep implementation.
Syntax
Following is the simple syntax for this function:
sleep EXPR
sleep
Return Value
This function returns Integer, number of seconds actually slept
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl
$num = 5;
while($num--){
sleep(1);
}
When above code is executed, it produces the following result:
485
Perl
socket
What is a Socket?
Socket is a Berkeley UNIX mechanism of creating a virtual duplex connection
between different processes. This was later ported on to every known OS
enabling communication between systems across geographical location running
on different OS software. If not for the socket, most of the network
communication between systems would never ever have happened.
Taking a closer look; a typical computer system on a network receives and
sends information as desired by the various applications running on it. This
information is routed to the system, since a unique IP address is designated to
it. On the system, this information is given to the relevant applications which
listen on different ports. For example an internet browser listens on port 80 for
information received from the web server. Also we can write our custom
applications which may listen and send/receive information on a specific port
number.
For now, let's sum up that a socket is an IP address and a port, enabling
connection to send and recieve data over a network.
To explain above mentioned socket concept we will take an example of Client Server Programming using Perl. To complete a client server architecture we
would have to go through the following steps:
To create a server
To create a client
Following diagram shows complete sequence of the calls used by Client and
Server to communicate with each other:
486
Perl
So socket function call issued by the server will be something like this:
use Socket
socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2]);
487
Perl
As the bind() is used by a server which does not need to know its own address
so the argument list looks like this:
use Socket
$port = 12345;
$server_ip_address = "10.12.12.168";
bind( SOCKET, pack_sockaddr_in($port, inet_aton($server_ip_address)))
or die "Can't bind to port $port! \n";
The or die clause is very important because if a server dies without outstanding
connections the port won't be immediately reusable unless you use the option
SO_REUSEADDR
using setsockopt() function.
Here pack_sockaddr_in() function is being used to pack the Port and IP
address into binary format.
488
Perl
$server_ip_address = "10.12.12.168";
connect( SOCKET, pack_sockaddr_in($port, inet_aton($server_ip_address)))
or die "Can't connect to port $port! \n";
489
Perl
If you connect to the server successfully then you can start sending your
commands to the server using SOCKET descriptor, otherwise your client will
come out by giving an error message.
use strict;
use Socket;
Perl
# accepting a connection
my $client_addr;
while ($client_addr = accept(NEW_SOCKET, SOCKET)) {
# send them a message, close connection
my $name = gethostbyaddr($client_addr, AF_INET );
print NEW_SOCKET "Smile from the server";
print "Connection recieved from $name\n";
close NEW_SOCKET;
}
To run the server in background mode issue the following command on Unix
prompt:
$perl sever.pl&
use strict;
use Socket;
491
Perl
my $line;
while ($line = <SOCKET>) {
print "$line\n";
}
close SOCKET or die "close: $!";
Now let's start our client at the command prompt which will connect to the
server and read message sent by the server and displays the same on the
screen as follows:
$perl client.pl
Smile from the server
NOTE: If you are giving actual IP address in dot notation then it is
recommended to provide IP address in the same format in both client as well as
server to avoid any confusion.
socketpair
Description
This function creates an unnamed pair of connected sockets in the specified
DOMAIN, of the specified TYPE, using PROTOCOL. If the system socketpair( )
function is not implemented, then it causes a fatal error.
Syntax
Following is the simple syntax for this function:
socketpair SOCKET1, SOCKET2, DOMAIN, TYPE, PROTOCOL
Return Value
This function returns 0 on failure ans 1 on success.
Example
Following is the example code showing its basic usage:
492
Perl
sort
Description
This function sorts LIST according to the subroutine SUBNAME or the anonymous
subroutine specified by BLOCK. If no SUBNAME or BLOCK is specified, then it
sorts according to normal alphabetical sequence.
If BLOCK or SUBNAME is specified, then the subroutine should return an integer
less than, greater than, or equal to zero, according to how the elements of the
array are to be sorted
Syntax
Following is the simple syntax for this function:
sort SUBNAME LIST
sort LIST
Return Value
This function returns sorted list.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
493
Perl
splice
Description
This function removes the elements of ARRAY from the element OFFSET for
LENGTH elements, replacing the elements removed with LIST, if specified. If
LENGTH is omitted, removes everything from OFFSET onwards.
Syntax
Following is the simple syntax for this function:
splice ARRAY, OFFSET, LENGTH, LIST
Return Value
This function returns:
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
@array
Perl
split
Description
This function splits a string expression into fields based on the delimiter specified
by PATTERN. If no pattern is specified whitespace is the default. An optional limit
restricts the number of elements returned.
A negative limit has the same effect as no limit. This function is often used in
conjunction with join() to create small text databases.
Syntax
Following is the simple syntax for this function:
split /PATTERN/, EXPR, LIMIT
split /PATTERN/
split
Return Value
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
Perl
sprintf
Description
This function uses FORMAT to return a formatted string based on the values in
LIST. Essentially identical to printf, but the formatted string is returned instead
of being printed.
Syntax
Following is the simple syntax for this function:
sprintf FORMAT, LIST
Return Value
This function returns SCALAR, a formatted text string.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
sqrt
Description
This function returns the square root of EXPR, or $_ if omitted. Most of the time,
this function returns a floating point number.
Syntax
Following is the simple syntax for this function:
sqrt EXPR
496
Perl
sqrt
Return Value
This function returns the Floating point number.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
$result = sqrt(4);
print " sqrt(4) is $result\n";
When above code is executed, it produces the following result:
sqrt(4) is 2
srand
Description
This function sets the seed value for the random number generator to EXPR or
to a random value based on the time, process ID, and other values if EXPR is
omitted
Syntax
Following is the simple syntax for this function:
srand EXPR
srand
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
497
Perl
#!/usr/bin/perl -w
srand(26);
print("Here's a random number:
srand(26);
print("Here's the same random number: ", rand(), ".\n");
When above code is executed, it produces the following result:
Here's a random number:
0.811688061411591.
stat
Description
This function returns a 13-element array giving the status info for a file,
specified by either FILEHANDLE, EXPR, or $_. The list of values returned is
shown below in Table. If used in a scalar context, returns 0 on failure, 1 on
success.
Note that support for some of these elements is system dependent.check the
documentation for a complete list.
Element Description
0
Inode number
10
11
12
Perl
Syntax
Following is the simple syntax for this function:
stat FILEHANDLE
stat EXPR
stat
Return Value
This function returns ARRAY, ($device, $inode, $mode, $nlink, $uid, $gid, $rdev,
$size, $atime, $mtime, $ctime, $blksize, $blocks)
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
study
Description
This function takes extra time to study EXPR in order to improve the
performance on regular expressions conducted on EXPR. If EXPR is omitted, uses
$_. The actual speed gains may be very small, depending on the number of
times you expect to search the string.
You can only study one expression or scalar at any one time.
499
Perl
Syntax
Following is the simple syntax for this function:
study EXPR
study
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
sub
Description
This function defines a new subroutine. The arguments shown above follow
these rules:
PROTO defines the prototype for a function, which will be used when the
function is called to validate the supplied arguments.
ATTRS define additional information for the parser about the subroutine
being declared.
Syntax
Following is the simple syntax for this function:
sub NAME PROTO ATTRS BLOCK# Named, prototype, attributes, definition
sub NAME ATTRS BLOCK # Named, attributes, definition
500
Perl
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
substr
Description
This function returns a substring of EXPR, starting at OFFSET within the string. If
OFFSET is negative, starts that many characters from the end of the string. If
LEN is specified, returns that number of bytes, or all bytes up until end-of-string
if not specified. If LEN is negative, leaves that many characters off the end of
the string.
If REPLACEMENT is specified, replaces the substring with the REPLACEMENT
string.
If you specify a substring that passes beyond the end of the string, it returns
only the valid element of the original string.
501
Perl
Syntax
Following is the simple syntax for this function:
substr EXPR, OFFSET, LEN, REPLACEMENT
Return Value
This function returns string.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
symlink
Description
This function creates a symbolic link between OLDFILE and NEWFILE. On
systems that don't support symbolic links, causes a fatal error.
Syntax
Following is the simple syntax for this function:
502
Perl
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage, first create one file
test.txt in /tmp directory and then try out following example it will create a
symbolic link in the same directory::
#!/usr/bin/perl -w
symlink("/tmp/text.txt", "/tmp/symlink_to_text.txt");
When above code is executed, it produces the following result:
Symbolic link gets created
syscall
Description
This function calls the system call specified as the first element of the list,
passing the remaining elements as arguments to the system call. If a given
argument is numeric, the argument is passed as an int. If not, the pointer to the
string value is passed.
Syntax
Following is the simple syntax for this function:
syscall EXPR, LIST
Return Value
This function returns -1 on failure of system call and values returned by system
function on success.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
503
Perl
require("syscall.ph");
$pid = syscall(&SYS_getpid);
sysopen
Description
This function is equivalent to the underlying C and operating system call open( ).
Opens the file specified by FILENAME, associating it with FILEHANDLE. The
MODE argument specifies how the file should be opened. The values of MODE
are system dependent, but some values are historically set. Values of 0, 1, and
2 mean read-only, write-only, and read/write, respectively. The supported
values are available in the Fcntl module, and are summarized in below Table.
Note that FILENAME is strictly a file name; no interpretation of the contents
takes place (unlike open), and the mode of opening is defined by the MODE
argument.
If the file has to be created, and the O_CREAT flag has been specified in MODE,
then the file is created with the permissions of PERMS. The value of PERMS must
be specified in traditional Unix-style hexadecimal. If PERMS is not specified, then
Perl uses a default mode of 0666 (read/write on user/group/other).
Flag
Description
O_RDONLY
Read only.
O_WRONLY
Write only.
O_RDWR
O_CREAT
O_EXCL
Perl
O_APPEND
O_TRUNC
O_NONBLOCK
Non-blocking mode.
O_NDELAY
Equivalent of O_NONBLOCK.
O_EXLOCK
O_SHLOCK
O_DIRECTOPRY
O_NOFOLLOW
O_BINARY
O_LARGEFILE
O_SYNC
O_NOCTTY
Syntax
Following is the simple syntax for this function:
sysopen FILEHANDLE, FILENAME, MODE, PERMS
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage:
505
Perl
sysread
Description
This function is the equivalent of the C/operating system function read() because
it bypasses the buffering system employed by functions like print, read, and
seek, it should only be used with the corresponding syswrite and sysseek
functions.
It read LENGTH bytes from FILEHANDLE, placing the result in SCALAR. If
OFFSET is specified, then data is written to SCALAR from OFFSET bytes,
effectively appending the information from a specific point. If OFFSET is
negative, it starts from the number of bytes specified counted backward from
the end of the string.
Syntax
Following is the simple syntax for this function:
sysread FILEHANDLE, SCALAR, LENGTH, OFFSET
Return Value
This function returns undef on error, 0 at end of file and Integer, number of
bytes read on success.
Example
Following is the example code showing its basic usage:
sysseek
Description
This function sets the position within FILEHANDLE according to the values of
POSITION and WHENCE.
506
Perl
This is equivalent of the C function lseek( ), so you should avoid using it with
buffered forms of FILEHANDLE. This includes the "FILEHANDLE" notation and
print, write, seek, and tell. Using it with sysread or syswrite is OK, since they too
ignore buffering.
The position within the file is specified by POSITION, using the value of WHENCE
as a reference point, as shown below in Table.
EEK_SET -> 0
Sets the new position absolutely to POSITION bytes
within the file
SEEK_CUR -> 1
Sets the new position to the current position plus
POSITION bytes within the file
SEEK_END -> 2
Sets the new position to POSITION bytes, relative to
the end of the file
Syntax
Following is the simple syntax for this function:
sysseek FILEHANDLE,POSITION,WHENCE
Return Value
This function returns undef on failure, a position of 0 is returned as the string 0
but true and Integer, new position (in bytes) on success.
Example
Following is the example code showing its basic usage:
507
Perl
system
Description
This function executes the command specified by PROGRAM, passing LIST as
arguments to the command.
The return value is the exit status of the program as returned by the wait
function. To obtain the actual exit value, divide by 256.
Syntax
Following is the simple syntax for this function:
system PROGRAM, LIST
system PROGRAM
Return Value
This function returns exit status of program as returned by wai
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
syswrite
Description
This function attempts to write LENGTH bytes from SCALAR to the file associated
with FILEHANDLE. If OFFSET is specified, then information is read from OFFSET
bytes in the supplied SCALAR. This function uses the C/operating system write( )
function, which bypasses the normal buffering.
508
Perl
Syntax
Following is the simple syntax for this function:
syswrite FILEHANDLE, SCALAR, LENGTH, OFFSET
Return Value
This function returns undef on error and Integer, number of bytes written on
success.
Example
Following is the example code showing its basic usage:
tell
Description
This function returns the current position of read pointer (in bytes) within the
specified FILEHANDLE. If FILEHANDLE is omitted, then it returns the position
within the last file accessed.
Syntax
Following is the simple syntax for this function:
tell FILEHANDLE
tell
Return Value
This function returns current file position in bytes.
Example
509
Perl
Following is the example code showing its basic usage, to check this function do
the followings:
Create a text file with "this is test" as content and store it into /tmp
directory.
#!/usr/bin/perl -w
telldir
Description
This function returns the current position of read pointer within the directory
listing referred to by DIRHANDLE. This returned value can be used by seekdir()
function.
Syntax
Following is the simple syntax for this function:
telldir DIRHANDLE
510
Perl
Return Value
This function returns the current position within the directory.
Example
Following is the example code showing its basic usage, we have only two files in
/tmp directory.:
#!/usr/bin/perl -w
opendir(DIR, "/tmp");
$dir = readdir(DIR);
print("Position after one read : ", telldir(DIR), "\n");
print "$dir\n";
seekdir(DIR,0);
$dir = readdir(DIR);
print "$dir\n";
print("Position after second read : " , telldir(DIR), "\n");
closedir(DIR);
When above code is executed, it produces the following result:
Position without read : 0
Position after one read : 1220443271
test.txt
test.txt
Position after second read : 1220443271
tie
Description
This function ties the VARIABLE to the package class CLASSNAME that provides
implementation for the variable type. Any additional arguments in LIST are
511
Perl
passed to the constructor for the entire class. Typically used to bind hash
variables to DBM databases.
Syntax
Following is the simple syntax for this function:
tie VARIABLE, CLASSNAME, LIST
Return Value
This function returns reference to tied object.
Example
Following is the example code showing its basic usage, we have only two files in
/tmp directory:
#!/usr/bin/perl -w
package MyArray;
sub TIEARRAY {
print "TYING\n";
bless [];
}
sub DESTROY {
print "DESTROYING\n";
}
sub STORE{
my ($self, $index, $value ) = @_;
print "STORING $value at index $index\n";
$self[$index] = $value;
}
sub FETCH {
my ($self, $index ) = @_;
print "FETCHING the value at index $index\n";
return $self[$index];
512
Perl
package main;
$object = tie @x, MyArray; #@x is now a MyArray array;
513
Perl
tied
Description
This function returns a reference to the object underlying the tied entity
VARIABLE. To understand tied check tie function.
Syntax
Following is the simple syntax for this function:
tied VARIABLE
Return Value
This function returns undef if VARIABLE is not tied to a package otherwise it
returns a reference to the object.
Example
Following is the example code showing its basic usage:
time
Description
This function returns the number of seconds since the epoch (00:00:00 UTC,
January 1, 1970, for most systems; 00:00:00, January 1, 1904, for Mac OS).
Suitable for feeding to gmtime and localtime.
Syntax
Following is the simple syntax for this function:
time
Return Value
This function returns integer, seconds since epoch.
514
Perl
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
$retval = time();
times
Description
This function returns a four-element list giving the user, system, child, and child
system times for the current process and its children.
Syntax
Following is the simple syntax for this function:
times
515
Perl
Return Value
This function
$childuser)
returns
ARRAY,
($usertime,
$systemtime,
$childsystem,
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
tr
Description
This is not a function. This is the transliteration operator; it replaces all
occurrences of the characters in SEARCHLIST with the characters in
REPLACEMENTLIST.
Syntax
Following is the simple syntax for this function:
tr/SEARCHLIST/REPLACEMENTLIST/
Return Value
This function returns number of characters replaced or deleted.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
Perl
print "$string\n";
When above code is executed, it produces the following result. Here option d is
used to delete matched characters.
b b
b.
truncate
Description
This function truncates (reduces) the size of the file specified by FILEHANDLE to
the specified LENGTH (in bytes). Produces a fatal error if the function is not
implemented on your system.
Syntax
Following is the simple syntax for this function:
truncate FILEHANDLE, LENGTH
Return Value
This function returns undef if the operation failed and 1 on success.
Example
Following is the example code showing its basic usage, it will truncate file
"test.txt" to zero length:
uc
Description
This function returns an uppercased version of EXPR, or $_ if not specified.
Check ucfirst() function which will return only first character in uppercase.
517
Perl
Syntax
Following is the simple syntax for this function:
uc EXPR
uc
Return Value
This function returns String in uppercase.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
ucfirst
Description
This function returns the value of EXPR with only the first character uppercased.
If EXPR is omitted, then uses $_.
Syntax
Following is the simple syntax for this function:
ucfirst EXPR
518
Perl
ucfirst
Return Value
This function returns String with first character in uppercase.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
umask
Description
This function sets the umask (default mask applied when creating files and
directories) for the current process. Value of EXPR must be an octal number. If
EXPR is omitted, simply returns the previous value.
Syntax
Following is the simple syntax for this function:
umask EXPR
umask
Return Value
This function returns the previous umask value.
519
Perl
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
undef
Description
This function undefines the value of EXPR. Use on a scalar, list, hash, function,
or typeglob. Use on a hash with a statement such as undef $hash{$key};
actually sets the value of the specified key to an undefined value.
If you want to delete the element from the hash, use the delete function.
Syntax
Following is the simple syntax for this function:
undef EXPR
undef
Return Value
This function returns undef.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
$scalar = 10;
@array = (1,2);
520
Perl
undef( $scalar );
undef( @array );
unlink
Description
This function deletes the files specified by LIST, or the file specified by $_
otherwise. Be careful while using this function because there is no recovering
once a file gets deleted.
Syntax
Following is the simple syntax for this function:
unlink LIST
unlink
Return Value
This function returns the number of files deleted.
Example
521
Perl
Following is the example code showing its basic usage, create two files t1.txt
and t2.txt in /tmp directory and then use the following program to delete these
two files:
#!/usr/bin/perl -w
unpack
Description
This function unpacks the binary string STRING using the format specified in
TEMPLATE. Basically reverses the operation of pack, returning the list of packed
values according to the supplied format.
You can also prefix any format field with a %<number> to indicate that you
want a 16-bit checksum of the value of STRING, instead of the value.
Syntax
Following is the simple syntax for this function:
unpack TEMPLATE, STRING
Return Value
This function returns the list of unpacked values.
Here is the table which gives values to be used in TEMPLATE.
Character
Description
522
Perl
A signed integer
An unsigned integer
A pointer to a string
Perl
A null byte
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
Perl
unshift
Description
This function places the elements from LIST, in order, at the beginning of
ARRAY. This is opposite function to shift().
Syntax
Following is the simple syntax for this function:
unshift ARRAY, LIST
Return Value
This function returns the number of new elements in ARRAY.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
@array
= ( 1, 2, 3, 4);
untie
Description
This function breaks the binding between a variable and a package, undoing the
association created by the tie function.
525
Perl
Syntax
Following is the simple syntax for this function:
untie VARIABLE
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
package MyArray;
sub TIEARRAY {
print "TYING\n";
bless [];
}
sub DESTROY {
print "DESTROYING\n";
}
sub STORE{
my ($self, $index, $value ) = @_;
print "STORING $value at index $index\n";
$self[$index] = $value;
}
sub FETCH {
my ($self, $index ) = @_;
print "FETCHING the value at index $index\n";
return $self[$index];
}
package main;
526
Perl
use
Description
This function imports all the functions exported by MODULE, or only those
referred to by LIST, into the name space of the current package. Effectively
equivalent to:
BEGIN
{
require "Module.pm";
Module->import();
}
Also used to impose compiler directives (pragmas) on the current script,
although essentially these are just modules anyway.
Note that a use statement is evaluated at compile time. A require statement is
evaluated at execution time.
527
Perl
If the VERSION argument is present between Module and LIST, then the use will
call the VERSION method in class Module with the given version as an argument.
The default VERSION method, inherited from the UNIVERSAL class.
Syntax
Following is the simple syntax for this function:
use MODULE LIST
use MODULE
use VERSION
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
use constant;
use diagnostics;
use integer;
use sigtrap
qw(SEGV BUS);
use strict
use subs
qw(afunc blurfl);
use v5.6.1;
use 5.6.1;
# ditto
use 5.006_001;
# ditto
528
Perl
utime
Description
This function sets the access and modification times specified by ATIME and
MTIME for the list of files in LIST. The values of ATIME and MTIME must be
numerical. The inode modification time is set to the current time. The time must
be in the numeric format (for example, seconds since January 1, 1970).
Syntax
Following is the simple syntax for this function:
utime ATIME, MTIME, LIST
Return Value
This function returns the number of files updated
Example
Following is the example code showing its basic usage, create a file t.txt in /tmp
directory and use the following program to set its modification and access time
to the current time.:
#!/usr/bin/perl -w
values
Description
This function returns the list of all the values contained in HASH. In a scalar
context, returns the number of values that would be returned. Uses the same
iterator, and therefore order, used by the each and keys functions.
Syntax
Following is the simple syntax for this function:
529
Perl
values HASH
Return Value
This function returns number of values in the hash in scalar context and list of
value in list context.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
4-3-2-1
vec
Description
This function uses the string specified EXPR as a vector of unsigned integers.
The NUMBITS parameter is the number of bits that are reserved for each entry
in the bit vector.
This must be a power of two from 1 to 32. Note that the offset is the marker for
the end of the vector, and it counts back the number of bits specified to find the
start. Vectors can be manipulated with the logical bitwise operators |, & and ^.
530
Perl
Syntax
Following is the simple syntax for this function:
vec EXPR, OFFSET, BITS
Return Value
This function returns the value of the bit field specified by OFFSET.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
$vec = '';
vec($vec,
3, 4) = 1;
vec($vec,
7, 4) = 10; # bits 4 to 7
vec($vec, 11, 4) = 3;
# bits 0 to 3
# bits 8 to 11
wait
Description
This function Waits for a child process to terminate, returning the process ID of
the deceased process. The exit status of the process is contained in $?.
Syntax
Following is the simple syntax for this function:
531
Perl
wait
Return Value
This function returns -1 if there are no child processes else the Process ID of
deceased process
Example
Following is the example code showing its basic usage:
waitpid
Description
This function waits for the child process with ID PID to terminate, returning the
process ID of the deceased process. If PID does not exist, then it returns -1. The
exit status of the process is contained in $?.
The flags can be set to various values which are equivalent to those used by the
waitpid() UNIX system call. A value of 0 for FLAGS should work on all operating
systems that support processes.
Syntax
Following is the simple syntax for this function:
waitpid PID, FLAGS
Return Value
This function returns -1 if process does not exist else Process ID of deceased
process.
Example
Following is the example code showing its basic usage:
Perl
wantarray
Description
This function returns true if the context of the currently executing function is
looking for a list value. Returns false in a scalar context.
Syntax
Following is the simple syntax for this function:
wantarray
Return Value
This function returns undef if no context and 0 if lvalue expects a scalar.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
sub foo {
return(wantarray() ? qw(A, B, C) : '1');
}
$result = foo();
# scalar context
@result = foo();
# array context
print("foo() in a
print("foo() in an array
context:
@result\n");
When above code is executed, it produces the following result:
foo() in a
scalar context: 1
foo() in an array
context:
533
Perl
A, B, C
warn
Description
This function prints the value of LIST to STDERR. Basically the same as the die
function except that no call is made to the exit and no exception is raised within
an eval statement. This can be useful to raise an error without causing the script
to terminate prematurely.
If the variable $@ contains a value (from a previous eval call) and LIST is
empty, then the value of $@ is printed with .\t.caught. appended to the end. If
both $@ and LIST are empty, then .Warning: Something.s wrong. is printed.
Syntax
Following is the simple syntax for this function:
warn LIST
Return Value
This function does not return any value.
Example
Following is the example code showing its basic usage:
#!/usr/bin/perl -w
write
Description
This function writes a formatted record, as specified by format to FILEHANDLE.
If FILEHANDLE is omitted, then writes the output to the currently selected
534
Perl
Syntax
Following is the simple syntax for this function:
write FILEHANDLE
write
Return Value
This function returns 0 on failure and 1 on success.
Example
Following is the example code showing its basic usage:
-X
Syntax
-X FILEHANDLE
-X
Return Value
1 if condition is true
535
Perl
0 if condition is false
-r
-w
-x
-o
-R
-W
-X
-O
-e
File exists.
-z
-s
-f
-d
File is a directory.
-l
-p
-S
File is a socket.
-b
-c
-t
-u
-g
-k
-T
-B
-M
-A
Perl
-C
Example
Try out following example with some file.
stat($filename);
print "Readable\n" if -r _;
print "Writable\n" if -w _;
print "Executable\n" if -x _;
print "Setuid\n" if -u _;
print "Setgid\n" if -g _;
print "Sticky\n" if -k _;
print "Text\n" if -T _;
print "Binary\n" if -B _;
y
Description
This function is identical to the tr/// operator; translates all characters in
SEARCHLIST into the corresponding characters in REPLACEMENTLIST. It does
character by character conversion
Syntax
Following is the simple syntax for this function:
y/SEARCHLIST/REPLACEMENTLIST/
Return Value
This function returns the number of characters modified.
Example
537
Perl
print "$string\n";
When above code is executed, it produces the following result:
THE CAT SAT ON THE MAT.
538