Mimir:Draft4 Chapter3

From Openitware
Jump to: navigation, search

Back to Main Textbook Index


Contents

Chapter 3: Imperative Programming

"Perl programming is an *empirical* science!" - Larry Wall

In this chapter you will learn:

  1. Imperative Paradigm
  2. Introduction to Python
  3. Introduction to Perl
  4. Basic Programming Concepts in Python
  5. Basic Programming Concepts in Perl

The Imperative Paradigm

Loop image.png

In chapter 2 you saw an overview of programming language that covers evolution of programming languages through its generations (1st, 2nd, 3rd,4th, and 5th), Compilers, Interpreter, Assembler, Parsing, Grammar, Variables and their Scope, Data Types, and six main Programming Paradigms.In this chapter, we look more closely at Imperative Programming Paradigm. We discuss A Quick History of Imperative Paradigm, what is Imperative programming and few languages that follows imperative approach with their examples.

In order to talk about programming languages, we organized them into categories. Though every single language is unique and share some common paradigm. The paradigm can better be described as a pattern or an archetype. Sorting out the languages according to their paradigm gives us the opportunity to observe them better. One of the paradigms is Imperative.

A Quick History of Imperative programming

The idea of imperative programming goes way back to 1950s, which is when the first high-level programming languages have been created. With 72 vacuum tube transistors and 18K of memory at disposal, the programs must have been as performant as possible. The only way to achieve it was to write programs in terms of step-by-step recipes for computer to execute.That's basically what imperative programming is all about — describing a program in terms of instructions which change its state. This 60-years-old style is still the most popular paradigm across many modern programming languages. Perl, Python, Basic, Ruby- these all languages follow imperative paradigm. [1]

An Introduction to Imperative programming

In computer science, imperative programming is a programming paradigm that describes computation in terms of statements that change a program state. In much the same way that imperative mood in natural languages expresses commands to take action, imperative programs define sequences of commands for the computer to perform. [2]

Programming with side effects is called Imperative programming. Imperative Programming is the traditional “step-by-step approach”. In other words, an imperative language specifies a series of instructions that the computer executes in sequence (do this, then do that). Let’s take a real world example. An Imperative sentence is a command.

        -Please walk the dog 
        -Please put your shoes in your room 

Imperative programming language are statement oriented and it is the task of programmer to specify explicitly which step a computer program has to perform in order to find the solution to the given problem. In Imperative Programming our program is structured out of instructions describing how the operations performed by a computer will happen. [3]


Imperative programming is mutating in nature, that is, they modify the state of the program/data so calling a function twice might not give the same result as the program might have changed the state. In Imperative languages you tell the computer how to change bits, bytes and words in its memory and in what order. An imperative language uses a sequence of statements to determine “how” to reach a certain goal. In other words, Imperative programming explicitly tells the computer "how" to accomplish it. These statements are said to change the state of the program as each one is executed in turn.

Examples of Imperative programming

The most common Imperative language consists of statements such as-

a = 10;
b = 5;
c = a + b;

The above example focus on evaluating expressions and storing results in a variable.

Imperative programming is closer to the machine representation, as it introduces memory state which the execution of the program’s actions will modify. We call these actions of programs instructions, and an imperative program is a list, or sequence, of instructions. The execution of each operation can alter the memory state. [4]

Let’s take an example of Imperative program in Python.

Greatest common divisor:

def gcd (x, y):
   r = 0
   while y > 0
      r = x % y
      x = y
      y = r
   return x
x y r
9702 945 0
945 252 252
252 189 189
189 63 63
63 0 0

The following table shows the change of states during each iteration of the while loop. We are diving x with y and storing the divisor in r (remember r initially was 0). Every time the execution take place the value stored in variable x, y, r change. After the execution is completed the value of x returned is 63.

Any Imperative Programming (IP) Languages can contain the following Characteristics:

  • Sequence of Statements.
  • Order of execution of Statements is very important.
  • They contain state.
  • They use both Immutable and Mutable Data.
  • They can change state.
  • They may have Side-effects.
  • Stateful Programming Model.
  • They directly change the state of Program.
  • They represent state with Data Fields.

At the heart of this paradigm – The main idea is of assignment (changing the value of a memory location and destroying its previous value).

             sum = sum + num; 

All imperative languages include assignment as a central concept. In addition to the central idea of assignment, the imperative paradigm supports:

  • Variable declarations
  • Expressions
  • Conditional statements
  • Loops
  • Procedural abstraction

Python

Introduction

Python is a general-purpose, interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum from 1985 to 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). [5] Python uses dynamic typing and a combination of reference counting and a cycle-detecting garbage collector for memory management. Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to Perl and PHP. You can actually sit at a Python prompt and interact with the interpreter directly to write your programs. Python supports the object-oriented style of programming, which is the technique of programming that encapsulates code within objects. Python is a great language for the beginner-level programmers and supports the development of a wide range of applications, from simple text processing to web browsers to games. Python has become one of the biggest and most popular languages today. Following its success, it has grown into a fully fledged programming language that has many features and capabilities included. [6]

One of the reasons Python is so popular is the easiness that it brings. Python is easy to learn, read and maintain. Python has few keywords, a simple structure, and a clearly defined syntax. This allows the the programmer to pick up the language quickly. Python code is more clearly defined and visible to the eyes. Lastly, Python's source code is fairly easy-to-maintain. Another thing that makes Python so popular is that the bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh. Since Python has more access to more people and machines, it has the likelihood of catching on more quickly. As stated earlier, Python has support for an interactive mode which allows interactive testing and debugging of snippets of code. Python is also extendable, meaning you can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient. A good programming language needs to be able to interact with a backend system, or database of some kind to be useful in today's environment. Luckily, Python provides interfaces to all major commercial databases. Python has a library that supports the creation of GUI applications. Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix. Lastly, Python provides a better structure and support for large programs than shell scripting. That is helped by the simplicity of the code and how easy it is to read.

This section of the chapter will give you a small taste of Python code, and how it relates to the interpretive programming paradigm. If you want to find out more about Python, the official documentation is a good first step to look into. Th official documentation can be found at this URL: https://docs.python.org/3/


Structure

Python is one of the most popular programming languages in use today. It is a very high level, interpreted language. That means that it is far away from machine code, and it is run line by line, and not compiled like C++ and does not use a virtual machine like Java. Like any other language, it can be written in regular notepad, a fancy text editor, or an IDE. Python files all have the .py extension. Python is a typeless language, meaning you don't have to specify whether something is an int, bool, string etc. Python does not use braces or brackets like many other programming languages. It uses indentation to determine whether something is part of a block. This could be an if statement, function, or loop of some kind. Python is also easier syntactically. It looks cleaner than most other languages because of the smaller amount of brackets, parenthesis, and semicolons being used. This makes it an easier language for beginning programmers who want to get into programming but don't want to be overwhelmed.

 if (x > y):
     print ("x is greater than y")
     x = x -1
 else:
     print ("x is less than or equal to y")

Data Types

Variables in Python follow the standard nomenclature of an alphanumeric name beginning in a letter or underscore, similar to how other languages do variable names. Just like in other programming languages, Python's variables are case sensitive. This means that myname and myName are different variables, stored at different locations in memory. Variables do not need to be declared and their data types are inferred from the assignment statement. This means that if you assign a string to a variable, Python automatically knows it is a string. If you assign the number 2 to a variable, it automatically knows it is an integer.

Python supports the following data types:

boolean 
integer 
long 
float 
string 
list 
object 

Below is an example of how you declare a variable in Python. Note again that you are not declaring a specific type. All you need to do is assign a variable a name and then assign whatever value you want afterwards, Python will take care of the rest for you.

For example:

My_variable = 10
my_int = 7
my_float = 1.23

Here we will be changing the value of a variable. In this example my_int will be changed from 7 to 3, by "reassigning" it, like this:

my_int = 7
my_int = 3

Now if you were to print my_int the value of it will be 3 instead of 7, since you reassigned the variable.


Strings

A string can contain letters, numbers, and symbols. Strings can be specified using single quotes or double quotes. Unlike other languages, single quotes do not represent a single character. In Python, strings are "immutable". This means they cannot be changed after they are created. This is similar to how it is done in Java, another programming language you have probably used.

For example:

Name = “Dunya”
Age = '30'

Math

Like any other language, Python is capable of computing mathematical equations. It can do addition, subtraction, multiplication, division, exponents and modulus arithmetic. It uses similar symbols to other programming languages.

Operation 	      Symbol
Addition	        +
Subtraction	        -
Multiplication	        *
Division	        /
Exponential 	        **
Modulus                 %

An example of some simple math you can do in Python:

addition = 1 + 23
subtraction = 10 – 2
multiplication = 0.5 * 0.5
division = 15 / 3
two_power_ten = 2**10 
modulus = 5 % 4

Boolean

Python is no different than other programming languages, in which boolean variables can only be true or false.

For example:

my_bool = True
b = False

Python uses the words "and", "or", "not" for its boolean operators rather than the symbols.

For Example:

a = 1>2 and 2!=2
print a 

The code above will print False.

The boolean operator "and" returns True when both sides of and are true.

For example:

1 < 2 and 2 < 3 is True
1 < 2 and 2 > 3 is False

The boolean operator "or" returns True when at least one expression on either side of or is true.

For example:

1 < 2 or 2 > 3 is True
1 > 2 or 2 > 3 is False 

The boolean operator "not" returns True for false statements and False for true statements.

For example:

not False     will evaluate to True
not 41 > 40   will return False.

Boolean Comparators

Boolean operations in Python also come with the typical six boolean comparison operators.

Equal to (==)
Not equal to (!=)
Less than (<)
Less than or equal to (<=)
Greater than (>)
Greater than or equal to (>=)

Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.

Example:

x = 3
print (x == 3) # prints out True
print (x != 5) # prints out False
print (x < 5) # prints out True
print (x > 10) # print out False

Note that (==) compares whether two things are equal, and (=) assigns a value to a variable.


Comments

A comment is a line of text that Python won't try to run as code. It's just for the programmer to read in order to make it easier to remember what something does, and make it easier for groups to work together.

  • There are two ways to write comments in Python:
    • Single Line Comments: The # sign is for comments.
    • Multi-Line Comments: for multi-line comments, you can include the whole block in a set of triple quotation marks:

Example of Single Line Comment:

# my_int is a variable
  my_int = 3
  print (my_int)

When you run the code above you will notice that the sentence followed by # symbol will not run

Example of Multi-Line Comments:

 """Dunya is doing the Python Coding Part.  This is a
    really long comment so I will use these symbols instead  """
 
 name = "Dunya"
 print (name)

When the code above is executed, the lines wrapped in """ will not be executed.


Print Statement

Print statements are a built in function in Python that allow the programmer to display something to the console. Keep in mind we will be showing examples from Python 3.x versions. This newest version requires you to place all print statements in parenthesis, while Python 2.7.x does not make you do this.

For example:

print ("Hello World!")
name = "Python"
print (name)

This is an example of two different prints. One print is printing a string, while the other is a variable that is assigned a string and prints the variable.

In Python you can combine strings by using the arithmetic symbol "+". The + operator between strings will 'add' them together, one after the other. Notice that there are spaces inside the quotation marks after (I) and (Love) so that we can make the combined string look like 3 words. If you did not have those spaces, it would combine all three words together. Combining strings together like this is called concatenation.

print "I " + "Love " + "Python"


Sometimes you need to combine a string with something that isn't a string. In order to do that, you have to convert the non-string into a string.

For example:

print "The value of pi is around " + str(3.14)

The code above will print: The value of pi is around 3.14

The str() method, which is a part of Python, converts non-strings into strings. In the above example, you convert the number 3.14 into a string and then you concatenate the strings together just like in the previous example.

There is another way to print a variable with a string by using %s instead of using concatenation:

For example:

name = "Dunya"
print "Hello %s" % (name)

The output for the code above will be: Hello Dunya

The % operator after a string is used to combine a string with variables. The % operator will replace a %s in the string with the string variable that comes after it.


Conditions

In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Python conditional statements give us this ability. They operate the same as in any other language. Python just differs syntactically.

If Statement

An if statement is a conditional statement that executes some specified code after checking if its expression is True. the general form of the (if) statement is:

if BOOLEAN EXPRESSION:
   STATEMENTS

A few important things to note about if statements:

  1. The colon (:) is significant and required. It separates the header of the compound statement from the body.
  2. The line after the colon must be indented. It is standard in Python to use four spaces for indenting.
  3. All lines indented the same amount after the colon will be executed whenever the BOOLEAN_EXPRESSION is true.

Here is an example:

if (8 < 9):
    print ("Eight is less than nine!")

In this example, 8 < 9 is the checked expression and print "Eight is less than nine!" is the specified code.

Else Statement

The else statement complements the if statement. An if/else pair says: "If this expression is true, run this indented code block; otherwise, run this code after the else statement." The else statement doesn't require an expression, it only runs if the previous expression in the if statement evaluated to True.

The syntax for an if else statement looks like this:

if BOOLEAN EXPRESSION:
   STATEMENTS_1        # executed if condition evaluates to True
else:
   STATEMENTS_2        # executed if condition evaluates to False

The statement inside the if block of an if else statement is executed if the Boolean expression evaluates to True. But the entire block of statements is skipped if the Boolean expression evaluates to False, and instead all the statements under the else will be executed.

For Example:

if (8 > 9):
   print "8 is greater than 9"
else:
   print "8 is less than 9"

The code above will skip the if block and will execute the (else) statement block because the condition in the (if) statement is evaluated to False.

Elif Statement

"Elif" is short for "else if." This statement is used if you want to check multiple conditions. If x is 1, if x is 2, if x is 3, etc.

The syntax of elif statement looks like:

if (choice == 'a'):
    print("You chose 'a'.")
elif (choice == 'b'):
    print("You chose 'b'.")
else:
    print("Invalid choice.")

For Example:

if (8 >= 9):
    print "False!"
elif (8 < 9):
    print "8 is less than 9!"
else:
    print "False"

In the example above, the elif statement is only checked if the original if statement is False.


Loops

All loops function in the same manner, They all loop over the same code block until some condition is deemed to be true. Python's loops are not much different compared to other languages.

while

The while loop is similar to an if statement. It executes the code inside of it if some condition is true. The difference is that the while loop will continue to execute as long as the condition is true. It will keep running for an unknown amount of times until the condition is met. In other words, instead of executing if something is true, it executes while that thing is true.

The general syntax for the while statement looks like this:

while BOOLEAN_EXPRESSION:
    STATEMENTS

For Example:

count = 0
if count < 5:
    print ("Hello, I am an if statement and count is", count)
while count < 5:
    print ("Hello, I am a while and count is", count)
    count += 1

The while statement decides when the loop will be executed. As long as count is less than 5, the loop will continue to execute, and increases count by 1. This happens over and over until count equals 5. When count is no longer less than 5, the loop will be exited.

The output for the code above will be

Hello, I am an if statement and count is 0
Hello, I am a while and count is 0
Hello, I am a while and count is 1
Hello, I am a while and count is 2
Hello, I am a while and count is 3
Hello, I am a while and count is 4

for

Another way to loop is the for loop. The syntax is as shown;

for LOOP_VARIABLE in SEQUENCE:
    STATEMENTS

The following example means "for each number i in the range 0 - 4, print i".

print "Counting..."
for i in range(5):
    print i

Output for the code above is:

Counting...
0
1
2
3

continue Skips the rest of the body of the loop for the current iteration and continue execution at the beginning of the next iteration.

break Ends the execution of the while loop.

Example:

for j in range(0,10):
    while (k < j):
        print "j = " + str(j) + " k = " + str(k)
        if (j == 1): 
            break
        k=k+1
        print "j equals k or j equals 1"

for-each

for x in array: statements

Loops over the array given by array. On each iteration, the value of the current element is assigned to x and the internal array pointer is advanced by one.

Example:

a = ["abc","def","ghi"]
for x in a:
  print x

File I/O (Input/Output)

Python also has the ability to open, read and write files on your computer. You only need to have a Python script running the same directory as your file, or as otherwise specified.

For example:

file = open(“testfile.txt”,”w”) 
file.write(“Hello World”) 
file.close() 

This example would open a file, looking for the name testfile.txt, with the "w" parameter, which stand for write. You could then write that string "Hello World", or any variable, array, etc to that file. You then close the file.

If you wanted to read from a file.

For example:

file = open(“testfile.text”, “r”) 
print (file.read())
file.close()

Notice how the structure is similar. We open the same file, but this time instead of "w" for write, we use "r" for read. Then we print out our "Hello World" line and then close the file.

This is just a simple example. You could do more with this, like writing a log to a text file, and then reading through that log and displaying it to the user. Keep files of old logs. Write variable values to a text log at certain points in the code. We just want to cover the basics here.


Functions

Functions in Python are defined with the following syntax
def funct(arg_1, arg_2, ..., arg_n):
   print "This is a function."
   return value

Any Python code, including other function and class definitions, may appear inside a function. Functions may also be defined within a conditional, but in that case the function's definition must be processed prior to its being called. Python does not support function overloading but does support variable number of arguments, default arguments, and keyword arguments. Return types are not specified by functions.

Example of a Double function:

function double(n):
   n = n*2
   return n
x = double(x)

Perl

Introduction

Perl was developed by Larry Wall in 1987 to be used as a general Unix scripting language. Perl stands for Practical Extraction and Report Language and falls under the imperative paradigm. Perl is influenced by following programming languages: AWK, Smalltalk, Lisp, C, C++, sed, Unix shell, and Pascal. Perl interpreter is written in C language and consists of approximately 150,000 lines of code.

Perl was initially created to be used as a utility programming language. It is particularly adept at processing the text files typically used as configuration files (converting between text formats).

Perl is an interpreted language. Perl has a short development cycle compared to compiled languages, but it will never execute as fast as a compiled language. Perl is not a strongly-typed language. A strongly-typed programming language is one that requires the type of a variable (int, float, char in other languages) to be explicitly declared. Perl can work on operating systems of 32-bit and 64-bit. Perl is case sensitive language, meaning that identifier names containing lowercase letters will be treated as being different and separate from those containing uppercase letters. Perl is a scripting language. It records its commands, repeating things in your own command line.


Structure

Like every other modern high-level programming language, Perl includes: scalars (variables), arrays, hashes, subroutines, loops, conditionals, regular expressions, objects, file I/O, and many more features. It is a dynamically typed language and uses leading sigils to identify different data types. Perl's vast feature set makes it a flexible language to code in. Since being a high-level imperative language, Perl syntax is executed by the interpreter as it's being read. Perl uses pound(#) to distinguish between comments and code, and a semi-colon(;) to signal the end of a line of code.

 $score = 0;
 print "Hello Player. \n";
 
 while ($score < 2)
 { 
    print "I win \n";
    $score = $score + 1;
 }

The above code has one scalar $score with assigned value of 0, in Perl scalars are represented by $ sigil. Next, the interpreter would read the print statement and since print is used to display content on to a screen, in this case it will output Hello Player and move to a new line which is represented by \n command. Now we come to a while loop, they are responsible for executing blocks of code multiple times until a specified condition evaluates to false. In the above while loop we want to output I win on a new line each time while loop executes. The condition being $score < 2 means that when scalar $score is less than 2 the code inside the while loop gets executed. Every time a while loop runs it increases $score by 1 which is represented by $score = $score + 1, this prevents an infinite loop since it will make the condition sooner or later evaluate to false. In the above example this will occur after the second time while loop executes as the value of $score will be 2, which is not less than 2. At this point the interpreter will end the while loop and continue to the next line of code.


Data Types

Perl has many data types, but the most common ones are scalars, arrays, and hashes. Scalar is an identifier of a memory location which contains information. It is a single value that may be a number, a string, a filehandler, or a reference. Array is simply a collection of scalars. Hash is a map that associates a key(string) to a value(scalars), also known as an associative array.

 Sigil   Type
   $     scalar
   @     array
   %     hash
 $name1 = "john";
 $name2 = "bob";
 $name3 = "david";
 $num = 100;

The above code shows three scalars named $name(1-3) with each one having a single string value represented by double quotes(" "). The fourth scalar has a number value of 100, numbers do not require double quotes unless it is being made into a string.

 @names = ($name1, $name2, $name3);
 or
 @names = ("john", "bob", "david");

Here we have two arrays with identical collection of data implemented in two different ways. First array is filled with the scalar identifiers from the first example, while the second array is filled with string values.

 %bio = ("john" => 50,
         "bob" => 37,
         "david" => 20,
        )

Hashes are arrays but they are more advanced. Hashes have the ability to associate a key with multiple values, its like an array within an array. In PHP language this is called an associative array. The above %bio hash has name strings as keys for the numerical value which we can assume to be persons age.


Print Statement

A print statement is found in most, if not all, modern high-level programming languages. Its function is to output information to the screen or a file in order to debug a program or simply make data visible to the user. It is one of the most frequently used statements in Perl. Print statement can be code to simply display a number or a string on the screen and complex as displaying large amounts of data from arrays, hashes, scalars, in a strictly specified format for easier reading/viewing of the data.

 print "Hello World!";

The above code outputs Hello World! to the screen. This is the simplest print statement.

 $name = "What"
 print "Hi, my name is " . $name . ".";

The above example shows how to concatenate a string using "." operator. It would output Hi, my name is What.


Conditionals

Conditionals are statements used to evaluate conditions on bases of true or false in order to perform different computations. Some of the most common conditional statements are if-else and else if statements. If-else statement evaluates one boolean condition and does the set of instructions provided under the true or false state. In else if statements, multiple conditions get to be evaluated and the first true condition gets to be executed and the rest of the conditions get skipped.

 $student = "freshman";
 
 if ($student eq "senior")
 {
    print "Almost to the finish line.";
 }
 else
 {
    print "So much more to learn."
 }

The above is an if-else statement. A scalar $student is assigned a string value freshman. If statements conditional is setup to evaluate if $student is equal to a string "senior", if it's true then it displays Almost to the finish line. Otherwise it displays the else code which is So much more to learn.

 $student = "senior";
 
 if ($student eq "sophomore")
 {
    print "Making progress.";
 }
 elsif ($student eq "junior")
 {
    print "Soon to be big dogs on campus.";
 }
 elsif ($student eq "senior")
 {
    print "Yay! Almost to the finish line.";
 }
 else
 {
    print "So much more to learn."
 }

Unlike if-else statement, else-if statements are a bit more complex in nature but they eliminate use of multiple if-else statements. The above example shows the Perl syntax of an else-if statement. In if-else example the interpreter had to only check one condition, in the above example there are multiple conditions to check. The first condition that is evaluated to "true", displays the given string. If once again all three conditions are false the interpreter will display the string specified under else statement. In this case $student eq "senior" condition evaluates to true thus Yay! Almost to the finish line. gets to be displayed on the screen.


Loops

Loops are used to repeat a statement multiple times until a condition evaluates to false. While loop acts like a repeating if statement, as long as the condition evaluates as true the code inside the while loop will run over and over. For loops are a bit different, they are used to loop through a preset number of times. Do-while loop is used to run the code inside it at least once before the condition gets evaluated. If the condition evaluates to true, the code inside gets to be executed again.

 $count = 0;
 while ($count < 10)
 {
    print "$count \n";
    $count++;
 )

The above example of a while loop will output current $count value on a new line and increment $count by one each time the while loop evaluates to true. In this case it will print 0-9 before while loop condition evaluates false and exits the loop.

 for ($count = 0; $count < 10; count++)
 {
    print "$count \n";
 }

The for loop syntax is a bit different than while loops but it has cleaner code. The for loop conditional needs three parameters to function. The first parameter is to initialize a $count scalar and assign a starting numerical value. The next parameter is the actual condition to be evaluated and finally the last parameter is to increment our scalar $count each loop run. The for loop in this example will output the same exact result as in the while loop example.

 $count = 0;  
 do
 {
    print "$count \n";
    $count++;
 } while ($count < 10);

Do-while loop syntax is a bit strange compared to while and for loops. Nonetheless it's a handy loop to have, sometimes you want the code to run at least once and then decide if the code needs to be run again or move to the next line of code. These are the situations in which the do-while loop is useful. It first runs the block of code inside the curly brackets and then evaluates the while condition to decided if it needs to run the block code again or not. The result returned from the above example will be same as the previous two examples.


File I/O (Input/Output)

Perl is a powerful language and with it come some very useful features. One of these features is file I/O, which gives the user the ability to read and write data to a file. This a great feature to have because it gives the developer the ability to store data in files rather than using memory if the data is not being used at that moment and time.

 open (FILE, "data.txt");
 
 while (<FILE>)
 {
    print "$_ \n";
 }
 
 close (FILE);

In Perl reading a file is very simple. The example above shows how to read the contents of a file and output each line on the screen. The Perl function open() is used to open the file stream. It requires two parameters. The first parameter is a filehandle name which we call FILE (this can be called anything). The second parameter is the actual file name (and location of the file if the file is not in the same directory as the Perl script). Once the file stream is open for reading, we use a while loop to read each line in the file and output it to the screen using a print statement. In Perl $_ is a default scalar that the while loop uses to store the data read from the file. After all the data is read and displayed on the screen, the file is closed by the close(FILE) function.


Subroutines

Subroutines are blocks of code that perform a specific task. Once created, they can be called multiple times within the program or implemented into other programs with ease. Subroutines eliminate code duplication, makes code cleaner and easier to maintain. Unlike in other programming languages where we need to specify the parameters (if any) when creating the subroutines/functions, Perl has a special way of creating parameters. In Perl when creating a subroutine no parameters need to be specified and yet when calling the subroutine parameters can be passed. The trick is that all parameters that get passed are stored inside a default @_ array. To use the parameter in the subroutine, a local variable is created and assigned to an element in the @_ array. For example:

 sub readFile
 {
    $name = $_[0];
    open (FILE, $name);
    while(<FILE>)
    {
       print "$_ \n";
    }
    close(FILE);
  }
  readFile("data.txt"); <--- calls the subroutine with one parameter 

Let's say we want to read multiple files in our script and we don't want to write duplicate code of reading a file. We create a subroutine that will make our code cleaner and maintainable. In the above example we will use the code from the File I/O section and create a subroutine out of it. In Perl subroutine is specified by keyword sub followed by the name we want to call the subroutine. Now, in order to open a specified file we need to use a parameter, and in Perl all parameters that are passed during the subroutine call are store in an array. To access the passed parameters we create a local scalar (in this case we called it $name) and we assign the default $_[0] array to it. We want the first parameter, so it's element 0. Now we have captured our parameter inside the $name scalar and we can use it throughout our subroutine. In our case the parameter represents the file name or its location that we want to read. To call the new subroutine we simply do this readFile("data.txt");

Summary

Imperative programming is a programming paradigm that describes computation in terms of statements that change a program state. This is in opposition to declarative programming, which expresses what the program should accomplish without prescribing how to do it in terms of sequences of actions to be taken. [7] An Imperative language is formed around a structure of code where you describe a series of statements for the computer to execute. These statements are giving directions to the computer in order for it to take specific actions following a certain order in the form of code blocks. The block of code is a part of code that is more of a sequence of statements that contain/form/code and is one of the innovations that came along with imperative languages. A paradigm can better be described as a pattern or an archetype and while all computer languages are unique, all share a common paradigm. "Perl" (created by Larry Wall in 1987) and "Python" (created by Guido van Rossum between 1985 and 1990) are two most widely known imperative programming languages. Developed to be used as a general Unix scripting language, Perl stands for Practical Extraction and Report Language. Perl includes: scalars (variables), arrays, hashes, subroutines, loops, conditionals, regular expressions, objects, file I/O, and many more features.

Key Terms

  • Imperative Paradigm: In computer science terminologies, imperative programming is a programming paradigm that describes computation in terms of statements that change a program state.
  • Conditionals: Conditionals are statements used to evaluate conditions on bases of true or false in order to perform different computations.
  • Subroutine: Subroutines are blocks of code that performs a specific task. Once created they can be called multiple times within the program or implemented into other programs with ease. Subroutines eliminate code duplication, makes code cleaner, and easier to maintain.

Problem Sets

A list of practice problems to do in Perl and in Python:

1) Write a program that determines whether a number inputted by the user is even or odd.

2) Write a program that takes in user input until the word "stop" is inputted. When nothing is inputted, print out all the words the user inputted.

3) Write a guessing game. Create a random number and then ask for user input. If the guess is below, print to the user the guess was below. Do the same for if it is too high.

4) Write a Fibonacci sequence.

5) Write a program that calculates factorials.

6) Write a program that prints out a string input backwards.

References

1. Adrian Kashivskyy. Imperative vs. Declarative Programming - Pros and Cons - Netguru, Netguru, Mar 2, 2015, www.netguru.co/blog/imperative-vs-declarative

2. en.wikipedia.org/wiki/Imperative_programming

3. Martin Grabmuller and Petra Hofstedt, "Turtle: A Constraint Imperative Programming Language", Technische Universitat Berlin, citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.59.9378&rep=rep1&type=pdf

4. Emmanuel Chailloux, Pascal Manoury and Bruno Pagano, "Développement d'applications avec Objective Caml", caml.inria.fr/pub/docs/oreilly-book/html/book-ora024.html

5. www.tutorialspoint.com/python/

6. www.tutorialspoint.com/python/python_overview.htm

7. www.csaldenham.co.uk/wp-content/uploads/2014/08/Programming-Languages.pdf


Top of Page - Prev Chapter - Next Chapter