Mimir:Draft3 Chapter3

From Openitware
Jump to: navigation, search

Back to Table of Contents


Chapter 3: Imperative Programming

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

In this chapter you will learn:

  1. Imperative Paradigm
  2. Perl, Python basics
  3. Basic Programming Concepts in Perl

The Imperative Paradigm

Loop image.png

(Enter in one to two paragraphs giving a brief overview of the chapter ahead.)

(START WIKIPEDIA) 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.

The term is used 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. Functional and logic programming are examples of a more declarative approach. (END WIKIPEDIA)

(Several paragraphs explaining each section, then as we get down into details move into sub sections. To have proper flow, which we will be adjusting mostly later, we can have the first section focus on that paradigm. The next section talk about the language we are focusing on in particular, etc, etc.)

In order to talk about programming languages we organized them into categories. Though every single language is unique some share a 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 the Imperative. A language that falls in the category of the imperative paradigm is called an Imperative Language. An Imperative language is formed around a structure of code. In Imperative you describe a series of statements for the computer to execute (as imperatives or commands). Your statements are giving directions to the computer so you pretty much order it to take specific actions following a certain order. The block of code is one of the innovations that came along with imperative language. When we talk about block of code we refer to a part of code that is more of a sequence of statements that contain/form/code a feature of our program/in our program/for our program.

"Perl" and "Python" are two most widely known imperative programming languages.

Python

Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL).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 Object-Oriented style or 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 WWW browsers to games.Python's features include:

  • Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly.
  • Easy-to-read: Python code is more clearly defined and visible to the eyes.
  • Easy-to-maintain: Python's source code is fairly easy-to-maintain.
  • A broad standard library: Python's bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh.
  • Interactive Mode:Python has support for an interactive mode which allows interactive testing and debugging of snippets of code.
  • Portable: Python can run on a wide variety of hardware platforms and has the same interface on all platforms.
  • Extendable: 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.
  • Databases: Python provides interfaces to all major commercial databases.
  • GUI Programming: 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.
  • Scalable: Python provides a better structure and support for large programs than shell scripting.

The language we will focus on for example is Perl.

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 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 interpreted. 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 strong type language. A strongly typed programming languages is one that requires the type of a variable to be explicitly stated. Perl can work on operating systems of 32-bit and 64-bit. Perl is case sensitive. This means 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. With Perls' vast features 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 single end off 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 and 2 is not less than 2 at which point the interpreter will end the while loop and continue to the next line of code.

Data Types

Perl has many data types but 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.

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

The above example show how to concatenate to string using "." operator. It would output Hi, my name is (value assigned to $name).

Conditionals

Conditionals are statements used to evaluate conditions on bases of true or false in order to perform different computations. 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 "Make 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. First parameter is to initializing a $count scalar and assign a starting numerical value. 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 than decided 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 for. 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, in other words 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. An example above shows how to read the contents of a file and output each line on the screen. Subroutine open() is used to open the file stream, it requires two parameters, first parameter is a filehandle name which we call FILE(can be anything), second parameter is a actual file name or 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 print statement. In Perl $_ is a default scalar that while loop uses to store the data read from the file. After all the data was read and displayed on the screen, file is closed by close(FILE) subroutine.

Subroutines

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. 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 would be created and assigned to an element in the @_ array. The example bellow shows this visually.

 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. So 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 it to the default $_[0] array and 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 our 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. 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

  • Imperitive Programming : What is imperitive programming? How is it different from declaritive programming? Are PERL and Python "compiled" languages? Describe why, or why not.
  • PERL Basics : What is a "typed" language? Is PERL a "typed" language? Why or why not?
  • Data Types : What is a "sigil"? What is a "scalar"? How does the scalar data type relate to arrays and hashes?
  • Basic Variables and Display : Create code to display a variable equal to 5000/11. Try displaying it to three decimal places. Now adjust the final display so that if the final decimal place is 5 or greater, that it rounds up.
  • Working with Arrays and Loops : Code an array of five string variables. Next create two loops, one that displays the names in original order, then a loop that displays it in reverse.
  • Conditionals - If/Else/Elsif : Much as you would use a Switch/Case statement, write code that takes a variable called $grade and uses if/elsif/else to display what the grade is ("A", "B-", "D" etc).
  • Subroutines and Recursive Coding : What is a "subroutine"? Why would you need them and when would you use them. Now, code a brief subroutine, in PERL, that creates a variable and states that place in the Fibonacci sequence.

Top of Page - Prev Chapter - Next Chapter