Chapter VI.3. Perl and Python

Perl and Python languages are both scripting languages meant to help programmers create something easily. The main difference between Perl and Python over traditional programming languages is their intended use.

Systems languages (such as C/C++) are meant to create standalone applications, such as operating systems or word processors, which is why systems languages are almost always compiled.

Scripting languages are meant more for linking different programs together, such as transferring data that someone types into a Web page and storing it in a database. As a result, scripting languages are almost always interpreted, which makes them more portable across different operating systems.

Systems languages are often known as type-safe because they force you to declare a specific data type (such as integer or string) for each variable. In contrast, scripting languages often allow a variable to hold anything it wants. One moment it may hold a string, the next an integer, and after that, a decimal number. Such typeless scripting languages give you greater flexibility at the possible expense of causing errors by variables containing unexpected data.

Perl's philosophy is that there's always more than one way to do it, so Perl often offers multiple commands that accomplish the exact same thing. The goal is to let you choose the way you like best.

Python takes the opposite approach and emphasizes a small and simple language that relies less on symbols (like C/C++) and more on readable commands to make programs easier to understand. Although Perl retains much of the syntax familiar to C/C++ programmers, Python abandons curly brackets and semicolons for a cleaner language that's simpler to read and write.

Both Perl and Python are used in Web applications but also for more specialized uses, such as text manipulation. Perl is particularly popular in the field of bioinformatics and finance whereas Python has been adapted as a scripting language for many graphics and animation programs.

Although system programming languages like C/C++ were designed to maximize the efficiency of computer equipment, languages like Perl and Python are designed to maximize the efficiency of programmers, who are now more expensive than computer equipment. When programmers need to write something in a hurry that doesn't involve manipulating the hardware of a computer, they often turn to Perl and Python.

Warning

Python is often associated with the British comedy troupe "Monty Python's Flying Circus." It's considered good form among Python programmers to slip in Monty Python references in their programs whenever possible.

The Structure of a Perl/Python Program

Because Perl and Python are interpreted languages, you can often type in commands a line at a time or type and save commands in a file. A simple Perl program might look like this:

print "This is a simple Perl program.
";
exit;

A Python program is even simpler:

print "This is a simple Python program."

Perl adapts the syntax of the C language including the use of semicolons at the end of each statement and the use of curly brackets to identify a block of commands. Python omits semicolons, and instead of using curly brackets to identify a block of comments, Python uses indentation. To identify a block of commands in Perl, use curly brackets like this:

if $x > 5
  {
  command1;
  command2;
  }

In Python, the same program might look like this:

if x > 5:
  command1;
  command2;

Warning

You can write both Perl and Python programs from a command-line prompt (meaning you type in commands one at a time) or saved as a file and then loaded into the interpreter. For testing short programs, typing them in one line at a time is probably faster, but for creating large programs, saving commands in a text file is easier.

Creating Comments

To write a comment in Perl, use the # symbol. Anything that appears to the right of the # symbol is treated as a comment, such as

# This is a comment
print "This is a simple Perl program.
";
exit; # This is another comment

In Python, you can also use the # symbol to create comments on a single line. If you want to create a comment covering multiple lines, use triple quotes to define the start and end of a comment, such as

""" This is a multiple line comment.
    The triple quotes highlight the beginning
    and the end of the multiple lines. """
print "This is a simple Python program."

Defining Variables

Both Perl and Python allow variables to hold any data types. In Perl, variable names begin with the dollar sign symbol, such as $myVar. Perl and Python are case-sensitive languages, so the Perl variable $myVar is considered completely different from $MYVar while the Python variable DueDate is completely different from the variable duedate.

Warning

If you misspell a variable in Perl or Python, both languages will treat the misspelled variable as a completely new and valid variable.

Using Operators

The three types of operators used are mathematical, relational, and logical. Mathematical operators calculate numeric results such as adding, multiplying, or dividing numbers, as shown in Table 3-1.

Table VI.3-1. Mathematical Operators

Mathematical Operator

Purpose

Example

+

Addition

5 + 3.4

-

Subtraction

203.9 - 9.12

*

Multiplication

39 * 146.7

/

Division

45/ 8.41

%

Modula division (returns the remainder)

35 % 9 = 8

**

Exponentiation

5**2 = 25

divmod (x,y) (Python only)

Returns both x / y and x % y

divmod (12,8) = (1,4)

Warning

When Python uses the division operator (/) to divide two integers, the result will be an integer, such as

9/4 = 2

If at least one number is a decimal, the result will also be a decimal, such as

9.0/4 = 2.25

Or

9/4.0 = 2.25

Relational operators compare two values and return a True or False value. The six relational operators available are shown in Table 3-2.

Table VI.3-2. Relational Operators

Relational Operator

Purpose

==

Equal

!=

Not equal

<

Less than

<=

Less than or equal to

>

Greater than

>=

Greater than or equal to

< = > (Perl only)

Comparison with signed result

Warning

The relational operator in Perl/Python is two equal sign symbols (==) whereas the relational operator in other programming languages is just a single equal sign symbol (=). If you only use a single equal sign to compare two values in Perl/Python, your program will work but not the way it's supposed to.

Perl offers a unique comparison with signed result operator (< = >), which compares two values and returns 0 (if the two values are equal), 1 (if the first value is greater than the second), or -1 (if the first value is less than the second), as shown in Table 3-3.

Table VI.3-3. Using Perl's Comparison with Signed Result Operator

Example

Result

5 < = > 5

0

7 < = > 5

1

2 < = > 5

-1

Logical operators compare two Boolean values (True [1] or False [0]) and return a single True or False value, as shown in Table 3-4.

Table VI.3-4. Logical Operators

Logical Operator

Truth Table

&& (Perl) and (Python)

1 and 1 = 1

1 and 0 = 0

0 and 1 = 0

0 and 0 = 0

|| (Perl) or (Python)

1 or 1 = 1

1 or 0 = 1

0 or 1 = 1

0 or 0 = 0

! (Perl) not (Python)

!1 = False (0)

!0 = True (1)

Increment and decrement operators

Perl (but not Python) has a special increment (++) and a decrement (--) operator, which simply adds or subtracts 1 to a variable. Typically, adding 1 to a variable looks like this:

j = 5;
i = j + 1;

The increment operator replaces the + 1 portion with ++, such as

j = 5;
i = ++j;

In the preceding example, the value of i is j + 1 or 6, and the value of j is also 6.

Warning

If you place the increment operator after the variable, such as

j = 5;
i = j++;

Now the value of i is 5, but the value of j is 6.

The decrement operator works the same way except that it subtracts 1 from a variable, such as

j = 5;
i = --j;

In the preceding example, the value of i is j - 1 or 4, and the value of j is also 4.

Warning

If you place the decrement operator after the variable, such as

j = 5;
i = j--;

Now the value of i is 5, but the value of j is 4.

Assignment operators

Most programming languages use the equal sign to assign values to variables, such as

i = 59;

However, Perl/Python also include combination assignment and mathematical operators, as shown in Table 3-5.

Table VI.3-5. Assignment Operators

Assignment Operator

Purpose

Example

+=

Addition assignment

i += 7 (equivalent to i = i + 7)

-=

Subtraction assignment

i -= 4 (equivalent to i = i - 4)

*=

Multiplication assignment

i *= y (equivalent to i = i * y)

/=

Division assignment

i /= 3.5 (equivalent to i = i / 35)

%=

Modulo assignment

i %= 2.8 (equivalent to i = i % 2.8)

Branching Statements

The simplest branching statement is an IF statement that only runs one or more commands if a Boolean condition is True. In Perl, the IF statement uses curly brackets to enclose one or more commands:

if (condition) {
  Command1;
  Command2;
  }

In Python, the IF statement uses indentation to enclose one or more commands:

if (condition):
  Command1
  Command2

To make the computer choose between two mutually exclusive sets of commands, you can use an IF-ELSE statement in Perl like this:

if (condition) {
  Command;
  Command;
  }
else {
  Command;
  Command;
  }

In Python, the IF-ELSE statement looks like this:

if (condition):
  Command
  Command
else:
  Command
  Command

The IF-ELSE statement only offers two choices. If you want to offer multiple choices, you can use the IF-ELSEIF statement, which uses two or more Boolean conditions to choose which of two or more groups of commands to run. In Perl, use the ELSIF keyword, such as

if (condition1) {
  Command;
  Command;
  }
elsif (condition2) {
  Command;
  Command;
  }
elsif (condition3) {
  Command;
  Command;
  }

In Python, use the ELIF keyword, such as

if (condition1):
  Command
  Command
elif (condition2):
  Command
  Command
elif (condition3):
  Command
  Command

Warning

Unlike other programming languages, neither Perl nor Python provides a SWITCH statement.

Looping Statements

A looping statement repeats one or more commands for a fixed number of times or until a certain Boolean condition becomes True. To create a loop that repeats for a fixed number of times, use the FOR loop, which looks like this:

for (startvalue; endvalue; increment) {
  Command;
  }

If you wanted the FOR loop to run five times, you could set the Start value to 1 and the End value to 5, such as

for (i = 1; i <= 5; i++) {
  Command;
  }

In Python, the FOR loop looks dramatically different:

for variable in (list):
  Command
  Command

To make a Python FOR loop repeat five times, you could do this:

for x in (1,2,3,4,5):
  print x

The preceding Python FOR loop would print

1
2
3
4
5

If you want a FOR loop to repeat many times (such as 100 times), it can be tedious to list 100 separate numbers. So Python offers a range() function that eliminates listing multiple numbers. To use the range() function to loop five times, you could do this:

for x in range(5):
  print x

Because the range() function starts with 0, the preceding Python FOR loop would print

0
1
2
3
4

Another way to use the range() function is by defining a lower and upper range like this:

for x in range(25, 30):
  print x

This FOR loop would print the numbers 25, 26, 27, 28, and 29. Rather than increment by one, you can also use the range() function to define your own increment, which can be positive or negative, such as

for x in range(25, 30, 2):
  print x

This FOR loop would print 25, 27, and 29.

If you don't know how many times you need to repeat commands, use a WHILE loop, which looks like this:

while (condition) {
  Command;
  Command;
}

If the condition is True, the loop runs at least once. If this condition is False, the loop doesn't run. In Python, the WHILE loop looks like this:

while (condition):
  Command
  Command

Warning

Somewhere inside a WHILE loop, you must have a command that can change the condition from True to False; otherwise, the loop will never end, and your program will appear to hang or freeze.

Creating Functions

In Perl and Python, every subprogram is a function that can return a value. The format of a typical Perl function looks like this:

sub functionname {
  Commands;
  return $value;
  }

When you pass parameters to a Perl function, that function can access them with the foreach keyword and the @_ array, such as

sub functionname {
  foreach $variablename (@_) {
    Commands;
  }
  return $value;
  }

The foreach $variablename (@_) line stores a list of parameters in the @_ array. Then the foreach command plucks each item from the @_ array and temporarily stores it in $variablename.

A typical Python function looks like this:

def functionname (variablename)
  Commands
  return value

If you don't want a function to return a value, omit the return line.

Perl Data Structures

Perl offers three data structures: arrays, hash arrays, and references. An array stores multiple items, identified by an index number. A hash array stores multiple items, identified by a key, which can be a number or a string.

Creating a Perl array

Like C/C++, Perl arrays are zero-based, so the first element of an array is considered 0, the second is 1, and so on. When you create a Perl array, you must name that array with the @ symbol. You can also define the elements of an array at the time you create the array, such as

@arrayname = (element1, element2, element3);

If you want to create an array that contains a range of numbers, you can list each number individually like this:

@numberarray = (1, 2, 3, 4, 5);

You can also use the range operator (..) to define the lower and upper bounds of a range, such as

@numberarray = (1..5);

To access the individual elements stored in an array, use the dollar sign ($) symbol in front of the array name, such as

@numberarray = (1..10);
$thisone = $numberarray[0];

The value stored in the $thisone variable is the first element of the @numberarray, which is 1.

One unique feature of Perl arrays is that you can use arrays to mimic a stack data structure with Perl's push and pop commands. To push a new item onto an array, you can use the push command:

push(@arrayname, item2add);

To pop an item off the array, use the pop command like this:

$variablename = pop(@arrayname);

Creating a Perl hash array

A hash array stores an item along with a key. Perl offers two ways to store values and keys. The first is like this:

%hasharray = (
  key1 => value1,
  key2 => value2,
  key3 => value3,
);

Notice that hash arrays are identified by the percentage (%) symbol.

A second way to define a hash array is like this:

%hasharray = ("key1", value1, "key2", value2, "key3",
   value3);

To retrieve data from a hash array, you need to know the key associated with that value and identify the hash array name by using the $ symbol like this:

$variable = $hasharray ("key1");

The preceding command would store the value associated with "key1" into the $variable.

Python Data Structures

Python offers tuples, lists, and dictionary data structures. Both tuples and lists contain a series of items, such as numbers and strings. The main difference is that items in a tuple can't be changed whereas items in a list can be changed. A dictionary stores values with keys, allowing you to retrieve values using its distinct key.

Creating a Python tuple

A tuple can contain different data, such as numbers and strings. To create a tuple, list all the items within parentheses like this:

tuplename = (item1, item2, item3)

To retrieve a value from a tuple, you must identify it by its index number, where the first item in the tuple is assigned a 0 index number, the second item is assigned a 1 index number, and so on. To retrieve the second item (index number 1) in a tuple, you could use this:

variablename = tuplename[1]

Creating a Python list

Unlike a tuple, a Python list lets you change, add, or delete items. To create a list, identify all items in the list by using square brackets like this:

listname = [item1, item2, item3]

To retrieve a value from a list, you must identify it by its index number, where the first item in the list is assigned a 0 index number, the second item is assigned a 1 index number, and so on. To retrieve the first item (index number 0) in a list, you could use this:

variablename = listname[0]

To add new items to a list, use the append command, such as

listname.append(newitem)

The append command always adds a new item at the end of a list. If you want to insert an item in a specific location in the list using its index number, use the insert command like this:

listname.insert(index, newitem)

To remove the first instance of an item in a list, use the remove command, such as

listname.remove(existingitem)

Warning

If a list contains identical items (such as 23), the remove command deletes the item with the lowest index number.

Creating a Python dictionary

A dictionary contains values and keys assigned to each value. To create, use curly brackets like this:

dictionaryname = {key1:value1, key2:value2, key3:value3}

To retrieve a value using its key, use the get command like this:

Variable = dictionary.name.get(key)

Using Objects

Both Perl and Python are true object-oriented programming languages (unlike C++), so you have no choice but to create and use objects in your programs. To create an object, you must define a class. In Perl, a typical class definition looks like this:

package className;
sub new {
  my $objectname = {
  Data;
  Data;
  };
  bless $objectname, $className;
  return $objectname;
sub methodname{
  Commands;
  Commands;
  };

In Python, a class looks like this:

class ClassName:
  Data
  Data
  def methodname (self):
    Commands
    Commands
    Commands

A class lists properties (data) along with one or more methods, which contain code for manipulating an object in some way.

After you define a class, you can create an object from that class by declaring a variable as a new class type. In Perl, you create an object by creating a constructor method commonly called new, such as

my $variablename = classname->new();

In Python, create an object like this:

objectname = new classname();

To use inheritance in Perl, use the @ISA variable inside a new class, such as

package newobject;
use class2inheritfrom;
@ISA = qw(class2inheritfrom);

To use inheritance in Python, identify the class to inherit from when you create a new class, such as

class ClassName (class2inheritfrom):
  Data
  Data
  def methodname (self):
    Commands
    Commands
    Commands

To inherit from multiple classes in Python, define additional classes, separated by a comma, such as

class ClassName (class2inheritfrom, anotherclass):
  Data
  Data
  def methodname (self):
    Commands
    Commands
    Commands
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset