Perl

From Bauman National Library
This page was last modified on 8 June 2016, at 20:10.
Perl
fraimed
Paradigm multi-paradigm: functional, imperative, object-oriented (class-based), reflective, procedural, event-driven, generic
Designed by Larry Wall
Developer Larry Wall
Typing discipline Dynamic
License GNU General Public License or Artistic License[1]
Website Template:Url
Influenced
Coffeescript,Template:Fact ECMAScript/JavaScript, Falcon, Groovy,Template:Fact Julia, LPC, Perl 6, PHP, Python, Ruby, Windows PowerShell

Perl is a general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development, network programming, GUI development, and more. Its major features are that it's easy to use, supports both procedural and object-oriented (OO) programming, has powerful built-in support for text processing, and has one of the world's most impressive collections of third-party modules.

History

Perl is the natural outgrowth of a project started by Larry Wall in 1986. Originally intended as a configuration and control system for six VAXes and six SUNs located on opposite ends of the country, it grew into a more general tool for system administration on many platforms. Larry Wall remains its principle architect. Although the first platform Perl inhabited was UNIX, it has since been ported to over 70 different operating systems including Windows 9x/NT/2000, MacOS, VMS, Linux, UNIX (many variants), BeOS, LynxOS, and QNX.

Installation

Unix and Linux

Here are the simple steps to install Perl on Unix/Linux machine.

  • Open a Web browser and go to http://www.perl.org/get.html.
  • Follow the link to download zipped source code available for Unix/Linux.
  • Download perl-5.x.y.tar.gz file and issue the following commands at $ prompt.
$ tar -xzf perl-5.x.y.tar.gz
$ cd perl-5.x.y
$ ./Configure -de
$ make
$ make test
$ make install

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.

Windows

Here are the steps to install Perl on Windows machine.

  • Follow the link for the Strawberry Perl installation on Windows http://strawberryperl.com.
  • Download either 32bit or 64bit version of installation.
  • Run the downloaded file by double-clicking it in Windows Explorer. This

brings up the Perl install wizard, which is really easy to use. Just accept the default settings and wait until the installation.

Macintosh

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.

  • Open a Web browser and go to http://www.perl.org/get.html.
  • Follow the link to download zipped source code available for Mac OS X.
  • Download perl-5.x.y.tar.gz file and issue the following commands at $

prompt.

$ tar -xzf perl-5.x.y.tar.gz
$ cd perl-5.x.y
$ ./Configure -de
$ make
$ make test
$ make install

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.

Execution

A Perl script can be created inside of any normal simple-text editor program. File must be saved with a .pl or .PL file extension in order to be recognized as a functioning Perl script.

#!/usr/bin/perl
# This will print "Hello, World"
print "Hello, world\n";
$chmod 0755 hello.pl
$./hello.pl
Hello, world

Syntax

Comments

Comments in Perl start with a hash symbol and run to the end of the line. 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.

# This is a comment in perl

=begin comment
Multy
line
comment
=cut

Quotes

You can use double quotes or single quotes around literal strings as follows:

print "Hello, world\n";
print 'Hello, world\n';

Only double quotes interpolate variables and special characters such as newlines \n, whereas single quote does not interpolate any variable or special character.

$a = 10;
print "Value of a = $a\n";   # Value of a = 10
print 'Value of a = $a\n';   # Value of a = $a\n$

Escaping Characters

Perl uses the backslash (\) character to escape any type of character that might interfere with code.

$result = "This is \"number\"";
print "$result\n";     # This is "number"
print "\$result\n";    # $result

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.

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. 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:

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.

$age = 25; # An integer assignment
$name = "John Paul"; # A string
$salary = 1445.50; # A floating point

Variable Context

Perl treats same variable differently based on Context, i.e., situation where a variable is being used.

@names = ('John Paul', 'Lisa', 'Kumar');
@copy = @names;    # John Paul Lisa Kumar
$size = @names;       # 3
Context Description
Scalar Assignment to a scalar variable evaluates the right-hand side in a scalar

context

List Assignment to an array or a hash evaluates the right-hand side in a list

context

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

Data Types

Perl is a loosely typed language and there is no need to specify a type for your data while using in your program. It has three basic data types: scalars, arrays of scalars, and hashes of scalars, also known as associative arrays.

Scalar

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. A scalar is created using $ sign.

Numbers

$integer = 200;
$negative = -300;
$floating = 200.340;
$bigfloat = -1.2E-23;
$octal = 0377;
$hexa = 0xff;

Strings

$var = "This is string scalar!";
$quote = 'I m inside single quote - $var';
$double = "This is inside single quote - $var";

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 (@). 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.

@ages = (25, 30, 40);
@names = ("John Paul", "Lisa", "Kumar");

$ages[0];    # 25
$names[2];  # Kumar

In Perl, List and Array terms are often used as if they're interchangeable. But the list is the data, and the array is the variable.

Array Creation

@array = (1, 2, 'Hello');
@var_10 = (1..10);
@var_abc = (a..z);
@array = qw/This is an array/;

Accessing Array Elements Array indices start from zero. You can also give a negative index, in which case you select the element from the end, rather than the beginning, of the array. @days = qw/Mon Tue Wed Thu Fri Sat Sun/;

print "$days[0]\n";    # Mon
print "$days[-1]\n";   # Sun
print "$days[-7]\n";   # Mon

Hashes

Hashes are unordered sets of key/value pairs that you access using the keys as subscripts. They are preceded by a percent sign (%).

%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);
$data{'John Paul'} # 45

Hashes Creation

%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40);

Example

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@keys = keys %data;
# adding an element to the hash;
$data{'Ali'} = 55;
# delete the same element from the hash;
delete $data{'Ali'};

References

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.

Reference

$scalarref = \$foo;
$arrayref  = \@ARGV;
$hashref = \%ENV;
$coderef = \&handler;
$globref = \*foo;
# anonymous array
$arrayref = [1, 2, ['a', 'b', 'c']];
# anonymous hash
$hashref = {
     'Adam'  => 'Eve',
     'Clyde' => 'Bonnie',
};
#  anonymous subroutine
$coderef = sub { print "Boink!\n" };

Dereference

Dereferencing returns the value from a reference point to the location. o 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.

$var = 10;
$r = \$var; # $r has reference to $var scalar
$$r; # value available at the location stored in $r.

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.

my $foo = 100;
$foo = \$foo;
$$foo; # REF(0x9aae38)

If ... Else ... Unless

A Perl if statement consists of a boolean expression followed by one or more statements.

If / Unless

if / unless (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{
 # Executes when the none of the above condition is true
}

Switch

The switch statement takes a single scalar argument of any type, specified in parentheses.

use Switch;
switch(argument){
 case 1 { print "number 1" }
 case "a" { print "string a" }
 case [1..10,42] { print "number in list" }
 case (\@array) { print "number in list" }
 case /\w+/ { print "pattern" }
 case qr/\w+/ { print "pattern" }
 case (\%hash) { print "entry in hash" }
 case (\&sub) { print "arg to subroutine" }
 else { print "previous case not true" }
}

Loops

While / Until

A while loop statement in Perl programming language repeatedly executes a target statement as long as a given condition is true.

while / until (condition) {
 statement(s);
}
do {
 statement(s);
}while( condition );

For loop

for ( init; condition; increment ){
 statement(s);
}

For each

@list = (2, 20, 30, 40, 50);
foreach $a (@list){
 print "value of a: $a\n";
}

Subroutines

A Perl subroutine or function is a group of statements that together performs a task. You can divide up your code into separate subroutines. How you divide up your code among different subroutines is up to you, but logically the division usually is so each function performs a specific task. Perl uses the terms subroutine, method and function interchangeably.

Usage

You can pass various arguments to a subroutine and they can be accessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on. You can create private variables called lexical variables at any time with the my operator. The local is mostly used when the current value of a variable must be visible to called subroutines.

# Global variable
$string = "Hello, World!";

# Function definition
sub Average{
    # $variable is invisible outside
    my $variable; 

    # Private variable
    local $string;

     # get total number of arguments passed.
     $n = scalar(@_);     $sum = 0;
     foreach $item (@_){$sum += $item;}
     $average = $sum / $n;
     return $average;
}

# Function call
Average(10, 20, 30);

Subroutines vs Functions vs Procedures

While reading programming literature and talking to programmers, you might run across the three terms "subroutines", "functions" and "procedures". Most of the time these are used interchangeably, but for the purists out there:

A function always returns a value, and, given the same arguments, always returns the same value. Functions are a lot like the functions you may have used in math class.

A procedure, unlike a function, may return no value at all. Unlike a function, a procedure often interacts with its external environment beyond its argument array. For instance, a procedure may read and write to files.

A subroutine refers to a sequence of instructions that may be either a function or a procedure.

OOP in Perl

Object Oriented concept in Perl is very much based on references and anonymous array and hashes.

An object within Perl is merely a reference to a data type that knows what class it belongs to. The object is stored as a reference in a scalar variable. Because a scalar only contains a reference to the object, the same scalar can hold different objects in different classes.

A class within Perl is a package that contains the corresponding methods required to create and manipulate objects.

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.

Perl provides a bless() function, which is used to return a reference which ultimately becomes an object.

package Person;

# constructor
sub new {
    my $class = shift;
    my $self = {
        _firstName => shift,
        _lastName  => shift,
        _ssn       => shift,
    };
    bless $self, $class;
    return $self;
}

# method
sub getFirstName {
    return $self->{_firstName};
}

#destructor
sub DESTROY {
    print "Person::DESTROY called\n"; 
}

Example usage:

use Person;
$object = new Person( "Mohammad", "Saleem", 23234345);
$firstName = $object->getFirstName();

References

  • "Perl Licensing". dev.perl.org. Retrieved 2011-01-08.