0% found this document useful (0 votes)
15 views125 pages

CSC205 PDF

Uploaded by

ajuwanate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views125 pages

CSC205 PDF

Uploaded by

ajuwanate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 125

Federal University of Technology, Akure

CSC205
STRUCTURED PROGRAMMING

https://odlearning.futa.edu.ng
Open and Distance Learning Centre, The Federal University of Technology Akure
P.M.B. 704, Akure, Ondo State, Nigeria
FEDERAL UNIVERSITY OF TECHNOLOGY, AKURE
ONDO STATE, NIGERIA

OPEN AND DISTANCE LEARNING CENTRE (ODLC)

B.Sc COMPUTER SCIENCE


PROGRAMME

CSC 205: STRUCTURED PROGRAMMING

i|Page
Course Development Team

Subject Matter Experts


School Department Expert
Computing Computer Science Prof. A. O. Adetunmbi
Prof. S. A. Oluwadare
Prof. O. O. Obe
Dr. A. E. Akinwonmi
Dr. S. I. Olotu

Instructional Designer
ODLC Mr. J. B. Oluwagbemi
ODLC Mr. P. K. Olotu

Language Editor
ODLC Dr. (Mrs.) F. Oguntade

E-Tutor
Department Name
Computer

ODLC Expert
Unit Name
INTEDH Dr. A. I. Makinde

Course Coordinator
Department Name
Computer Prof. S. A. Oluwadare

Programme Coordinator
Dr. E. O. Ibam

Centre Director
Prof. F. I. Alao

ii | P a g e
CSC 205 - Study Guide

Introduction
CSC 205: Structured Programming is a 2-credit unit course for students studying towards
acquiring a Bachelor of Science in Computer Science and other related disciplines.

The course is divided into 8 study sessions and 20 study units. It provides an overview of
programming languages and their types; and explains the principles of abstraction and
modularity. The elements of structured programming are then given before outlining the
steps in program design and execution. An introduction to the PERL programming language
follows with how to use and apply operators and control statements. Functions and arrays in
PERL are then discussed, finally ending the course with a study of structures and pointers in
PERL programming language.

Recommended Study Time


This course is a 2 unit course divided into 9 study sessions. You are enjoined to spend at least
3 hours in studying the content of each study unit

What You are About to Learn in This Course


This course is a 2 unit course divided into 9 study sessions. You are enjoined to spend at least
2 hours in studying the content of each study unit.

Course Aim
This course is designed for a semester in Structure Programming Language using
PERL for undergraduate Computer Science. The course covers general concepts
Structure Programming Language. The course covers the basic features needed to be
good Computing field and how to write Structure Programming language in PERL.

Course Objectives
It is important to note that each unit has specific objectives. Students should study
them carefully before proceeding to subsequent units. Therefore, it may be useful to
refer to these objectives in the course of your study of the unit to assess your progress.
You should always look at the unit objectives after completing a unit. In this way, you
can be sure that you have done what is required of you by the end of the unit.
However, below are overall objectives of this course. On completing this course, you
should be able to:
 Define programs and classify programming languages
 State the advantages and disadvantages of high and low–level languages

iii | P a g e
 State the characteristics of a good program
 List the various phases of program development.
 Explain the steps involved in problem definition and analysis
 Describe functions and Procedures in program
 Illustrate a typical function structure for sorting numerical arrays in PERL
language.
 Define a class in Object–oriented programming
 Explain the abstraction costs and benefits
 Define modularity in programming.
 State the advantages of modular programming approach
 Describe the real-life application of modularity concept.
 Explain the importance of header file, module implementation and main
program in PERL programming language.
 Illustrate the structure of interface file in PERL language declarations.
 State the purpose of IMPORT and the EXTERN macros in PERL language
program declaration
 State the advantages and disadvantages of structure programming
 Describe the examples of programming paradigms.
 State the various programming paradigms
 Describe each of the named programming paradigms and programming
languages associated with it.
 Give a brief history of PERL Programming Language.
 Explain the taxonomy of PERL programming types
 Explain the importance of studying PERL programming language.
 Describe the characteristics and uses of PERL Program.
 Illustrate the structure of a PERL Programming language.
 Explain the contents of the PERL program structure.
 Explain the processes involved in compilation and execution of PERL
program.

iv | P a g e
 Describe the sample input/ output steps used in program compilation and
execution.
 List the character set in PERL
 Apply the character set in constructing variables and identifiers
 Differentiate between a variable and a keyword
 Explain what a data type is
 Define a constant
 State the rules for constructing integer constants
 State the rules for constructing real constants
 State the rules for constructing real constants expressed in exponential form
 State the rules for constructing character constants
 Format your input
 Format your output
 Differentiate between the output of integer float
 Differentiate between the input of integer float
 Define an operator
 Use operators in expressions
 Mention the various operators applicable to PERL programming
 Describe each of the operators
 State the three control structures inherent in PERL
 State the generic syntax for the various structures
 Use these structures to write a program code or a block of code
 Describe each of the structure
 Manually simulate a program code involving the structures
 Differentiate between monolithic Vs modular Programming
 State the disadvantages of monolithic Programming
 State the advantages of modular Programming
 Declare a function
 Outline the various function categories
 Differentiate between a user define functions vs standard function.

v|Page
 Differentiate between call by value and call by reference
 Describe an array
 Differentiate between one-dimensional and a two-dimensional array
 Initialize one-dimensional, two-dimensional and multi-dimensional arrays
 State the syntax of array declaration
 Define a string
 Differentiate between a string and a character
 Manipulate string
 Mention some commonly used string input/output library functions
 Read and write string
 Declare a string variable
 Understand PERL structures and pointers
 Know how to define and use structures and pointers in PERL

Walking through This Course


To complete this course, you are required to study all the units, the recommended text books,
and other relevant materials. Each unit contains some self-assessment exercises and tutor
marked assignments, and at some point in this course, you are required to submit the tutor
marked assignments. There is also a final examination at the end of this course. Stated below
are the components of this course and what you have to do.

Course Materials
The major components of the course are:
1. Course Guide
2. Study Units
3. Text Books
4. Tutor Marked Assignments
5. Presentation Slides
6. Interactive DVD
7. Electronic Lecture Materials via Learning Management System (LMS)
8. Printed Lecture Materials

vi | P a g e
Study Units
There are 14 Study Units and 6 Study Sessions in this course. They are:
Study Session 1: Programing Languages

Unit 1.1 Computer Programming

Unit 1.2 Characteristics of a Good Program

Unit 1.3 Phases of Program Development (Programming)

Study Session 2: Abstraction and Modularity

Unit 2.1 Introduction to Abstraction

Unit 2.2 Modular Programming

Unit 2.3 Modular Interface

Study Session 3: Elements of Structured Programming

Unit 3.1 Overview of Structured Programming

Unit 3.2 Programming Language Paradigms

Study Session 4: Structured Programming with PERL

Unit 4.1 Overview of PERL

Unit 4.2 Executing a PERL Program

Study Session 5: Introduction to PERL Programming Language

Unit 5.1 Subroutines and Functions

Unit 5.2 Pattern Matching

Study Session 6: Operators and Control Statements

Unit 6.1 Modules and Databases

Unit 6.2 SOAP and Socket Programming

Walking through This Course

The following texts and Internet resources links will be of enormous benefits to you in
learning this course:

Fundamentals of Structured Programming, Lubia Vinhas, 2016

vii | P a g e
Structured Programming with C++ by Kjell Backman, 2012

National Open University of Nigeria: Introduction to Computer Science.

www.cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf

www.academia.edu/25814963/An_Introduction_to_Computer_Science

Assignment File
The assignment file will be given to you in due course. In this file, you will find all the details
of the work you must submit to your tutor for marking. The marks you obtain for these
assignments will count towards the final mark for the course. Altogether, there are tutor
marked assignments for this course.

Presentation Schedule
The presentation schedule included in this course guide provides you with important dates for
completion of each tutor marked assignment. You should therefore endeavour to meet the
deadlines.

Assessment
There are two aspects to the assessment of this course. First, there are tutor marked
assignments; and second, the written examination. Therefore, you are expected to take note of
the facts, information and problem solving gathered during the course. The tutor marked
assignments must be submitted to your tutor for formal assessment, in accordance to the
deadline given. The work submitted will count for 40% of your total course mark. At the end
of the course, you will need to sit for a final written examination. This examination will
account for 60% of your total score.
Assignment Marks
Assignment 1- 6 40% of the course marks
End of Course Assessment 60% of overall course marks
Total 100% of course materials

Tutored Marked Assignments (TMAs)


There are TMAs in this course. You need to submit all the TMAs. The best 10 will therefore
be counted. When you have completed each assignment, send them to your tutor as soon as
possible and make certain that it gets to your tutor on or before the stipulated deadline. If for
any reason you cannot complete your assignment on time, contact your tutor before the
assignment is due to discuss the possibility of extension. Extension will not be granted after
the deadline, unless on extraordinary cases.

Final Examination and Grading


The final examination for CSC 205 will last for a period of 2 hours and have a value of 60%
of the total course grade. The examination will consist of questions which reflect the Self

viii | P a g e
Assessment Questions, In-text Questions and tutor marked assignments that you have
previously encountered. Furthermore, all areas of the course will be examined. It would be
better to use the time between finishing the last unit and sitting for the examination to revise
the entire course. You might find it useful to review your TMAs and comment on them
before the examination. The final examination covers information from all parts of the
course. Most examinations will be conducted via Computer Based Testing (CBT).
The following are practical strategies for working through the course
1. Read the course guide thoroughly

2. Organize a study schedule. Refer to the course overview for more details. Note the
time you are expected to spend on each unit and how the assignment relates to the
units. Important details, e.g. details of your tutorials and the date of the first day of the
semester are available. You need to gather together all this information in one place
such as a diary, a wall chart calendar or an organizer. Whatever method you choose,
you should decide on and write in your own dates for working on each unit.

3. Once you have created your own study schedule, do everything you can to stick to it.
The major reason that students fail is that they get behind with their course works. If
you get into difficulties with your schedule, please let your tutor know before it is too
late for help.

4. Turn to Unit 1 and read the introduction and the objectives for the unit.

5. Assemble the study materials. Information about what you need for a unit is given in
the table of Contents at the beginning of each unit. You will almost always need
both the study unit you are working on and one of the materials recommended
for further readings, on your desk at the same time.

6. Work through the unit, the Contents of the unit itself has been arranged to provide a
sequence for you to follow. As you work through the unit, you will be encouraged to
read from your set books

7. Keep in mind that you will learn a lot by doing all your assignments carefully. They
have been designed to help you meet the objectives of the course and will help you
pass the examination.

8. Review the objectives of each study unit to confirm that you have achieved them. If
you are not certain about any of the objectives, review the study material and consult
your tutor.

9. When you are confident that you have achieved a unit’s objectives, you can start on
the next unit. Proceed unit by unit through the course and try to pace your study so
that you can keep yourself on schedule.

10. When you have submitted an assignment to your tutor for marking, do not wait for its
return before starting on the next unit. Keep to your schedule. When the assignment is
returned, pay particular attention to your tutor’s comments, both on the tutor marked

ix | P a g e
assignment form and also written on the assignment. Consult you tutor as soon as
possible if you have any questions or problems.

11. After completing the last unit, review the course and prepare yourself for the final
examination. Check that you have achieved the unit objectives (listed at the beginning
of each unit) and the course objectives (listed in this course guide).

Tutors and Tutorials


There are several hours of tutorial provided in support of this course. You will be notified of
the dates, time and location together with the name and phone number of your tutor as soon
as you are allocated a tutorial group. Your tutor will mark and comment on your assignments,
keep a close watch on your progress and on any difficulties you might encounter and provide
assistance to you during the course. You must mail your tutor marked assignment to your
tutor well before the due date.
At least two working days are required for this purpose. They will be marked by your
tutor and returned to you as soon as possible. Do not hesitate to contact your tutor by
telephone, e-mail or discussion board if you need help. The following might be circumstances
in which you would find help necessary: contact your tutor if:
i. You do not understand any part of the study units or the assigned readings.
ii. You have difficulty with the self-test or exercise.
iii. You have questions or problems with an assignment, with your tutor’s comments on
an assignment or with the grading of an assignment.
You should endeavor to attend the tutorials. This is the only opportunity to have face to face
contact with your tutor and ask questions which are answered instantly. You can raise any
problem encountered in the course of your study. To gain the maximum benefit from the
course tutorials, have some questions handy before attending them.

You will learn a lot from participating actively in discussions.

WISHING YOU ALL THE BEST

x|Page
Table of Contents

Course Development Team i


Course Code: Study Guide ii
Table of Contents x
STUDY SESSION 1: PROGRAMMING LANGUAGES 1
Unit 1.1: Computer Programming 1
Unit 1.2: Characteristics of a Good Program Phases of Program Development 5
(Programming)
STUDY SESSION 2: ABSTRACTION AND MODULARITY 9
Unit 2.1: Introduction to Abstraction 9
Unit 2.2: Modular Programming 14
STUDY SESSION 3: ELEMETS OF STRUCTURED PROGRAMMING 20
Unit 3.1: Overview of Structured Programming 20
Unit 3.2: Programming Language Paradigms 24
STUDY SESSION 4: STRUCTURED PROGRAMMING PERL 27
Unit 4.1: Overview of PERL 27
Unit 4.2: Executing PERL Program 41
STUDY SESSION 5: INTRODUCTION TO PERL PROGRAMMING 47
LANGUAGE
Unit 5.1: Subroutines and Functions 47
Unit 5.2: Pattern Matching 57
STUDY SESSION 6: OPERATORS AND CONTROL STATEMENTS 68
Unit 6.1: Modules and Databases 68
Unit 6.2: SOAP and Socket Programming 76

xi | P a g e
Study Session 1

Study Session 1: Programing Languages


Content
Introduction
Learning Outcomes for Study Session 1
Learning Activities
Unit 1.1: Computer Programming
1.1.1 Classification of Programming Languages
1.1.2 Low Level Language
1.1.3 High Level Language
1.1.4 Features of High-Level Language
Unit 1.2: Characteristics of a Good Program and Phases of Programming
1.2.1 Characteristics of a Good Program
1.2.2 Phases of Program Development
Summary for Study Session 1
Glossary of Terms
Pilot Answers
Self-Assessment Questions (SA Qs) for Study Session 1
References/Further Reading

1
Study Session 1: Programing Languages
Introduction
A program is a finite set of sequenced instructions or commands given to a computer in order
to carry out a particular task. To write a program for the computer to carry out these
instructions, there must be a means of communication. Humans communicate via natural
languages such as English, French, Chinese etc. Likewise, to communicate with the
computer, we also use languages known as programming languages. Programming is the
art of program writing using a particular programming language. It can also be said to be the
process of writing a set of instructions in sequential manner using programming language to
control the activity of a computer system.

Learning Outcomes for Study Session 1


When you have studied this session, you should be able to:
1.1 Define programs and classify programming languages,
1.2 State the advantages and disadvantages of high- and low-level languages

2
Unit 1.1

Computer Programming
A computer programming language is an artificial language which is used in writing a set of
formal instructions to control the activities of a computer system. There are two main types
of computer programming languages; these are: Low-level language and High-level
language. Low-level languages also known as machine language, are machine dependent
and makes fast and efficient use of the computer. It requires no translator to translate the
code. It is directly understood by the computer. On the contrary, writing a program in high-
level language does not require knowledge of the computer in which the program is run.
Hence, high-level languages are machine independent, and which programs are portable to
other computers, and very easy to learn and write.

In Computer Programming, what are the classifications of programming language?

1.1.1 Classification of Programming Languages


There are two major types of computer programming languages: the low-level language and
high-level language.

1.1.2 Low level language


This type of language is closer to the machine compared with the human or natural language.
The two major examples are the Machine language and the Assembly language.

Machine Language: This is the only language computer understands. It is the native
language of the computer. The computer directly executes a program written in machine
language. These programs are coded using strings of 0’s and 1’s. It doesn’t need a translator.

Advantages of Machine Language

• Machine language makes fast and efficient use of the computer.


• It requires no translator to translate the code. It is directly understood by the
computer.
Disadvantages of Machine Language

• Very bulky
• They require much time for writing and reading.

3
• They are prone to error which is difficult to detect and correct.
• Very difficult to learn.
• Can only run on the computer it is designed (i.e., it is machine dependent)

Box 1.1: Computer Programming

A computer programming language is an artificial language which is used in writing a set of

formal instructions to control the activities of a computer system.

Assembly Language: Assembly Language uses MNEMONICS (symbols) to represent data


and instructions. Such program eliminates problems associated with machine language.
Computer cannot execute directly a program written in assembly language; it requires a
translator called assembler. Assembler is a special program designed to translate a program
written in assembly language to a machine language equivalent.

Advantages of Assembly Language

• It allows complex jobs to run in a simpler way.


• It is memory efficient, as it requires less memory.
• It is faster in speed, as its execution time is less.
• It is mainly hardware oriented.
• It requires less instruction to get the result.
• It is used for critical jobs.
Disadvantages of Assembly Language
• It is machine dependent; the programmer must be knowledgeable in both subject area
and the operations of the machine.
• It is cumbersome though less cumbersome than that of machine language.
• Very expensive to develop
• It consumes time

1.1.3 High Level Language


A high-level language is a problem-orientated programming language. The source
programs are written in human readable languages like English instead of mere symbols. In

4
other words, a high-level language is a convenient and simple means of describing the
information structures and sequences of actions required to perform a particular task.

Advantages of High-Level Language

• No knowledge of the computer in which the program will be run is required


• The programs are portable
• Very easy to learn and write
Disadvantages of High-Level Language
• It takes additional translation times to translate the source to machine code.
• High level programs are comparatively slower than low level programs.
• Compared to low level programs, they are generally less memory efficient.
• Cannot communicate directly with the hardware

Box 1.2: High Level Programming Language

A high-level language (HLL) is a programming language such as PERL, or FORTRAN that


enables a programmer to write programs that are more or less independent of a particular type
of computer. Such languages are considered high-level because they are closer to human
languages and further from machine languages.

1.1.4 Features of High-Level Language


• Machine independent
• Problem oriented
• Ability to clearly reflect the structure of program written in it.
• Readability
• Programs are portable.
What are the examples of high-level programming languages available?
Examples of High-level Languages are PERL, FORTRAN, COBOL, QBASIC, VISUAL
BASIC, JAVA, PASCAL etc.

Pilot Question 1.1


Classify programming languages and explain the different categories

5
Unit 1.2

Characteristics of a Good Program and Phases of Programming

The principles of data processing set the pace for obtaining the requirements of a good
program. In data processing, three phases are critical: The input, processing and the output
phases. Input constitutes what instruction and data goes into the system. Processing has to do
with what logic or tools are required to manipulate the data. Hence, we expect certain
characteristics from a good program or tool intended to process the data to yield informed
output.

There are various phases in the development of computer programs. These phases must be
strictly adhered to, to ensure a reliable, efficient program devoid of syntax and semantic
errors.

What are the good characteristics of good programming?

Example 1: Supposed you are asked to develop an application, what are the steps-by-step
procedure in writing a good programming?
Solution:
1.2.1 Characteristics of Good Programming
• Portability/Transferability: Must be able to work on any computer machine.
• Reliability: It can be relied upon to do what it is expected to do.
• Efficiency/cost saving: It must not cost more than its benefits and enables problem to
be solved appropriately, quickly and efficiently.
• Clarity and Simplicity: It should be as simple as possible to understand.
• Understandability/Readability: It must be readable and understandable by other
programmers and end users.
• Flexibility/Adaptability/Maintainability: A good program must be flexible adaptable
and maintainable in order to suit user’s need. Modification must be possible and very
easy.

6
1.2.2 Phases of Program Development (Programming)
The process of producing a computer program (software) may be divided into eight phases or
stages:
 Problem definition/Analysis
 Selection or development of an algorithm
 Designing the program
 Coding the programming statements
 Compiling/Compilation stage
 Testing/Running and Debugging the program
 Documentation.
 Maintenance

Box 1.3: Phases of Programming

In data processing, three phases are critical: The input, processing and the output phases.

What are the definitions of the eight phases of programming

(i) Problem Definition/Analysis Stage: There is need to understand the problem that
requires a solution. The need to determine the data to be processed, form or type of
the data, volume of the data, what to be done to the data to produce the
expected/required output.
(ii) Selection or development of an algorithm: An algorithm is the set of steps required
to solve a problem written down in English language.
(iii) Designing the program: In order to minimize the amount of time to be spent in
developing the software, the programmer makes use of flowchart. Flowchart is the
pictorial representation of the algorithm developed in step 2 above. Pseudocode IPO
chart (input processing output) and HIPO (Hierarchical Input Processing and
Output) chart may be used in place of flowchart or to supplement flowchart.
(iv) Coding the statement: This involves writing the program statements. The
programmer uses the program flow chart as a guide for coding the steps the
computer will follow.

7
(v) Compiling: There is need to translate the program from the source code to the
machine or object code if it is not written in machine language. A computer
program is fed into the computer first, then as the source program is entered, a
translated equivalent (object program) is created and stored in the memory.
(vi) Running, Testing and Debugging: When the computer is activated to run a program,
it may find it difficult to run it because errors (syntax, semantics or logic, or
runtime) might have been committed. Manuals are used to debug the errors. A
program that is error free is tested using some test data. If the program works as
intended, real life data are then loaded.
(vii) Documentation: This is the last stage in software development. This involves
keeping written records that describe the program, explain its purposes, define the
amount, types and sources of input data required to run it. List the Departments and
people who use its output and trace the logic the program follows.
(viii) Maintenance: All the activities that occur after the completion of the program come
under the program maintenance. Program maintenance includes the following:
Finding and correcting the errors; Modifying the program to enhance it – i.e.,
adapting to some new concepts or when there is a change in the hardware or
operating system; Update the documentation; Add new features and functions;
Remove useless or redundant parts of code.

Pilot Question 1.2


i. List any five characteristics of a good program
ii. Explain the phases or stages of program (or software) development
iii. Describe the content of program documentation

8
Summary of Study Session 1
A computer program is a set of instruction given to a computer to carry out a particular task.
Computer programs are written using programming languages. These languages can be
classified into low-level (i.e., machine and assembly languages) and high-level languages.
Machine language uses 0s and 1s while assembly uses mnemonics. The high level languages
use mathematical symbols in combination with English like words. Both the low-level and
high-level programming languages have their advantages and disadvantages. These are
stated in the main contents of the unit.

The characteristics of a good program are outlined which include: transferability, reliability,
efficiency, cost saving, simplicity, understandability, readability, flexibility, adaptability,
maintainability.

What are the Phases of Program Development?

The Phases of Program Development are:

 Problem definition/Analysis
 Selection or development of an algorithm
 Designing the program
 Coding the programming statements
 Compiling/Compilation stage
 Testing/Running and Debugging the program
 Documentation.
 Maintenance

9
GLOSSARY OF TERMS
A high-level language (HLL): HLL is a programming language such as PERL, or
FORTRAN that enables a programmer to write programs that are more or less independent of
a particular type of computer. Such languages are considered high-level because they are
closer to human languages and further from machine languages.
Computer Programming: A computer programming language is an artificial language
which is used in writing a set of formal instructions to control the activities of a computer
system.
Machine Language: This is the only language computer understands. It is the native
language of the computer. The computer directly executes a program written in machine
language.
Low level language: This type of language is closer to the machine compared with the
human or natural language. The two major examples are the Machine language and the
Assembly language.

10
Pilot Answers
Pilot Answer 1.1
There are two major types of computer programming languages: the low-level language and high-
level language.

High Level Language: A high-level language is a problem-orientated programming language. The


source programs are written in human readable languages like English instead of mere symbols.

Low level language: This type of language is closer to the machine compared with the human or
natural language

Pilot Answer 1.2


List any five characteristics of a good program
• Portability/Transferability: Must be able to work on any computer machine.
• Reliability: It can be relied upon to do what it is expected to do.
• Efficiency/cost saving: It must not cost more than its benefits and enables problem to be
solved appropriately, quickly and efficiently.
• Clarity and Simplicity: It should be as simple as possible to understand.
• Understandability/Readability: It must be readable and understandable by other programmers
and end users.
Explain the phases or stages of program (or software) development
• Selection or development of an algorithm: An algorithm is the set of steps required to solve a
problem written down in English language.
• Designing the program: In order to minimize the amount of time to be spent in developing the
software, the programmer makes use of flowchart. Flowchart is the pictorial representation of
the algorithm developed in step 2 above. Pseudocode IPO charts (input processing output) and
HIPO (Hierarchical Input Processing and Output) chart may be used in place of flowchart or
to supplement flowchart.
• Coding the statement: This involves writing the program statements. The programmer uses
the program flow chart as a guide for coding the steps the computer will follow.
• Compiling: There is need to translate the program from the source code to the machine or
object code if it is not written in machine language. A computer program is fed into the
computer first, then as the source program is entered, a translated equivalent (object program)
is created and stored in the memory.
• Running, Testing and Debugging: When the computer is activated to run a program, it may
find it difficult to run it because errors (syntax, semantics or logic, or runtime) might have
been committed. Manuals are used to debug the errors. A program that is error free is tested
using some test data. If the program works as intended, real life data are then loaded.

Describe the content of program documentation


• Documentation: This is the last stage in software development. This involves keeping written
records that describe the program, explain its purposes, define the amount, types and sources
of input data required to run it.

11
Self-Assessment Questions (SAQs) for Study Session 1
This unit introduced the students to the basic knowledge of computer programming. It
defined computer program and discussed the two major classifications of programming
languages (the low- and high-level programming languages).

When designing a program, a conscious effort should be made to build in some


characteristics that makes for a good and functional program. In this unit some of these
characteristics are stated. The phases involved in the development of a program are
enumerated. The steps for problem definition and analysis are also explained.

You can now assess how well you have achieved the learning outcomes for this study
session by answering the following questions. You can check your answers with the Notes
on the Self-Assessment questions at the end of this session.

1. Explain type of Programming Language


2. State 5 differences between high level language and machine language
3. Explain any five characteristics of a good program
4. Explain the phases or stages of program (or software) development
5. Describe the content of program documentation

12
References/Further Reading

Fundamentals of Structured Programming, Lubia Vinhas, 2016 -


http://wiki.dpi.inpe.br/lib/exe/fetch.php?media=cap390:fund_prog12.pdf

Structured Programming with C++ by Kjell Backman, 2012 - https://tfetimes.com/wp-


content/uploads/2015/04/structured-programming-with-c-plus-plus.pdf

www.cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf -
https://cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf

Introduction to computer Science -


www.academia.edu/25814963/An_Introduction_to_Computer_Science

13
Study Session 2

Study Session 2: Abstraction and Modularity


Content
Introduction
Learning Outcomes for Study Session 2
Learning Activities
Unit 2.1: Introduction to Abstraction
2.1.1 Abstraction
2.1.2 Functions and Procedures
2.1.3 Classes
2.1.4 Abstraction Costs and Benefits
Unit 2.2: Modular Programming
2.2.1 Modularity
2.2.2 Advantages of Using Modular Programming Approach
2.2.3 Modular Programming in Preal
Summary for Study Session 2
Glossary of Terms
Pilot Answers
Self-Assessment Questions (SA Qs) for Study Session 2
References/Further Reading

14
Study Session 2: Abstraction and Modularity
Introduction
As programmers began to write instructions that were equivalent to a few bytes, the level of
thinking in terms of what the computer was doing on a functional level raised the level of
abstraction. Statements and structured code can be thought of as assembly language
operations, at a higher level of abstraction. Statements are collected to form functions,
procedures, subroutines, or methods. The abstraction or grouping code and its data structures
is called object-oriented programming. However, the clump of code and data definitions is
called a class in most programming languages. In many software maintenance projects, the
cost of the additional performance of low levels of abstraction is far higher than the cost of
the computer cycles that would be required to run the program.

A module is basically a set of interrelated files that shares their implementation details but
hide it from the outside world. The main advantages of modular programming approach,
includes ease of use, reusability, and ease of maintenance. Modularity is applicable in real
life such as electrical devices that can plug into any outlet/socket. Modularization is a method
to organize large programs in smaller parts, i.e., the modules. Every module has a well-
defined interface toward client modules that specifies how “services” provided by this
module are made available. Moreover, every module has an implementation part that hides
the code, and any other private implementation details the clients’ module.

Learning Outcomes for Study Session 2


At the end of this study session, you should be able to:
2.1 Describe functions and Procedures in program
2.2 Illustrate a typical function structure for sorting numerical arrays in PERL
programming language.
2.3 Define a class in Object–oriented programming
2.4 Explain the abstraction costs and benefits
2.5 Define modularity in programming, state the advantages of modular
programming approach and describe the real-life application of modularity
concept.

15
Unit 2.1

2.1.1 Abstraction
The history of programming has experienced rising levels of granularity. Decades ago,
programmers manipulated individual bits of codes. Then the assembly language was
invented, and programmers began to write instructions that were equivalent to a few bytes.
The advantage was clear: Instead of thinking in terms of essentially meaningless 1s and 0s,
you could think in terms of what the computer was doing on a functional level—move this
value to that memory location, multiply these two bytes together.
This is called raising the level of abstraction. Every time you raise the level of abstraction in
a programming language, you get more clearer, structured program (as measured in terms of
bits) for less work. The language at which you communicate with the computer can also be
altered into something closer to the way we communicate in English.

Each unit of the level of abstraction has a contract or agreement: The language makes an
exact promise of what the computer will do when the unit is executed. For the following
assembly language instruction:

LD (BC), A the language promises that it will move the value from the register named A into
the place in memory pointed to by registers B and C. Obviously, this is only a very small
piece of what you want the computer to do, such as word processing, video processing, etc.
but it’s a lot clearer and easier to use than its binary equivalent: 00000010

It may not seem any shorter or easier to remember LD (BC), A; but each of the letters here
has an explicit and easily remembered meaning: LD is short for LOAD; A, B, and C refer to
some registers, and (BC) refers to a way to do indirection into memory. 00000010 may be
just seven 0s and a 1, but the order is both critical and hard to memorize. Swapping two of
the bits to 00000100 means INC B (increment the B register), which is totally different.

Box 2.1: Abstraction

Abstraction is one of the four cornerstones of Computer Science. It involves filtering out –
essentially, ignoring - the characteristics that we don't need in order to concentrate on those
that we do

16
2.1.2 Functions and Procedures
Statements and structured code can be thought of as assembly language operations, at a
higher level of abstraction. The next level of abstraction is to group statements into
operational units with contracts of their own. Statements are collected to form functions,
procedures, subroutines, or methods, as they are called in various languages. The beauty
about functions is that they limit even further the amount of code required to understand a
piece of code.

2.1.3 Classes
Structured programming and functions neatly solve some of the problems of maintenance by
limiting the amount of code you must look at in order to understand any given line. There’s
still one way that far off pieces of code can affect a particular line of code. The sort example
given earlier sorts only integers, which is not a particularly interesting job.

Why would you ever want to sort just a list of numbers?


More likely, you want to be able to sort a list of objects of some kind, based on an integer
key. Or, more generally, you’d like to be able to sort on any key, so long as you can reliably
compare any two objects.

Even before object-oriented programming, there were ways to group chunks of data into
functional units. In C, these units are called structs. However, structs don’t have any reliable
way to compare them. You need some level of abstraction a little higher than provided by
structs that allows you to tell which of two structs should come first. The abstraction of
grouping code and its data structures is called objectoriented programming. The clump of
code and data definitions is called a class in most programming languages.

Box 2.2: Function

A function is simply a “chunk” of code that you can use over and over again, rather than
writing it out multiple times. Functions enable programmers to break down or decompose a
problem into smaller chunks, each of which performs a particular task.

17
Box 2.3: Subroutines

Subroutines are small blocks of code in a modular program designed to perform a particular
task. Since a subroutine is in itself a small program, it can contain any of the sequence ,
selection and iteration constructs.

What are the costs and benefits of abstraction?

2.1.4 Abstraction Costs and Benefits


In many software maintenance projects, the cost of the additional performance of low levels
of abstraction is far higher than the cost of the computer cycles that would be required to
run the program. As a maintenance programmer, your time is extremely expensive. The time
of your users is even more expensive (since there are usually more of them than there are for
you), so correctness of the program is key. If users lose work or time waiting for your
software to be corrected, that easily represents lots of money.

Higher levels of abstraction lead to improved maintenance, simply because there’s less code.
The less code, the less you have to read to understand it. Certainly, there are limits to this, as
50 lines of clear code is preferable to 10 lines of total obscurity. In general, however, by
using higher levels of abstraction, improved maintainability is gained.

Of course, there’s a downside to these higher levels of abstraction in terms of performance.


The more flexible a program is, the harder it is to optimize. As a maintainer, you’ll have to
find the balance that works best. The old dictum of C.A.R. Hoare that “Premature
optimization is the root of all evil” is particularly applicable to abstraction. Choose your
levels appropriately and optimize those parts that can’t be made to function at the level of
abstraction you choose. The payoff is in programming time, both in development and
maintenance, and that makes users happy.

Pilot Question 2.1


i. What is Abstraction?
ii. Write a function to select the largest of 3 numbers

18
Unit 2.2

2.2.1 Modularity
Modular programming is the process of subdividing a computer program into separate sub-
programs. A module is a separate software component. It can be used in a variety of
applications and functions with other components of the system.

Some programs may have thousands or millions of lines and to manage. For such programs
such programs it becomes quite difficult as there might be too many of syntax errors or
logical errors present in the program, so to manage such programs, the concept of modular
programming is essential. The modular programming concept permits that each sub-
module contains something necessary to execute only one aspect of the desired functionality.
Modular programming therefore places emphasis on breaking of large programs into small
problems to increase the maintainability, readability of the code and to make the program
handy for any changes in future.

Box 2.4: Modular Programming

Modular programming is the process of subdividing a computer program into separate sub-
programs

What are the advantages of using Modular Programming?

2.2.2 Advantages of Using Modular Programming Approach


Ease of Use: This approach allows simplicity, as lines of program code can be accessed in
the form of modules, rather than focusing on the entire thousands and millions of lines code.
This allows ease in debugging the code and prone to less error.

Reusability: It allows the user to reuse the functionality with a different interface without
typing the whole program again.

Ease of Maintenance: It helps in less collision at the time of working on modules, helping a
team to work with proper collaboration while working on a large application.

19
Below is an example of a Real-life Example of Modules
Let’s consider a familiar modular system. Consider the electrical devices (microwaves,
electric kettles, washers, dryers, etc.) that can plug into any outlet/socket. None of these
device care if they are plugged into the electrical outlet in your house or your neighbor’s
house or your office, etc. They are designed to do their specific task and functionality when
they are plugged in and when the power is on, regardless the place they are in.

Application modules should follow the same philosophy. Regardless of the application and
even regardless of what application they plugged into, they should do their specific task and
only their specific task.

Also, in exactly the same way that an electrical device can easily be unplugged from the wall
outlet, a code module should be designed in such a way that it can easily be decoupled and
removed from your application.

Furthermore, as the removal of one electrical device has no impact on the functionality of
other devices that are plugged into your electrical system, the removal of a code module or a
series of code modules from your application should not have any effect on the functionality
of the other parts of your application.
This decoupling should also have no effect on the application, other than perhaps just losing
the specific functionality that was provided by that particular module or group of modules in
the application.

2.2.3 Modular Programming in PERL


Building a medium- to large-sized program usually requires you to divide tasks into several
smaller, more manageable, and more interactive pieces. (A rule of thumb is that each "piece"
should be about one or two printed pages in length, but this is just a general guideline.) An
analogy can be made to building a microarray machine, which requires that you construct
separate interacting pieces such as housing, temperature sensors and controls, robot arms to
position the pipettes, hydraulic injection devices, and computer guidance for all these
systems.

20
Subroutines
Subroutines divide a large programming job into more manageable pieces. Modern
programming languages all provide subroutines, which are also called functions, or macros
in other programming languages.

A subroutine lets you write a piece of code that performs some part of a desired computation
(e.g., determining the length of DNA sequence). This code is written once and then can be
called frequently throughout the main program. Using subroutines speeds the time it takes to
write the main program, makes it more reliable by avoiding duplicated sections (which can
get out of sync and make the program longer), and makes the entire program easier to test. A
useful subroutine can be used by other programs as well, saving you development time in
the future. As long as the inputs and outputs to the subroutine remain the same, its internal
workings can be altered and improved without worrying about how the changes will affect
the rest of the program. This is known as encapsulation.

The benefits of subroutines that I've just outlined also apply to other approaches in software
engineering. PERL modules are a technique within a larger umbrella of techniques known as
software encapsulation and reuse. Software encapsulation and reuse are fundamental to
object-oriented programming.

Box 2.5: PERL

Perl is a family of script programming languages that is similar in syntax to the C language. It
is an older, open source, general use, interpreted language. Perl was developed with usability
in mind. Its efficient design lets developers do a lot with a little bit of code.

A related design principle is abstraction, which involves writing code that is usable in many
different situations. Let's say you write a subroutine that adds the fragment TTTTT to the end
of a string of DNA. If you then want to add the fragment AAAAA to the end of a string of
DNA, you have to write another subroutine. To avoid writing two subroutines, you can write
one that's more abstract and adds to the end of a string of DNA whatever fragment you give it
as an argument. Using the principle of abstraction, you've saved yourself half the work.

Here is an example of a PERL subroutine that takes two strings of DNA as inputs and
returns the second one appended to the end of the first:

21
sub DNAappend {
my ($dna, $tail) = @_;

return($dna . $tail);
}
This subroutine can be used as follows:
my $dna = 'ACCGGAGTTGACTCTCCGAATA';
my $polyT = 'TTTTTTTT';

print DNAappend($dna, $polyT);


This subroutine can be used as follows:
my $dna = 'ACCGGAGTTGACTCTCCGAATA';
my $polyT = 'TTTTTTTT';

print DNAappend($dna, $polyT);


If you wish, you can also define subroutines polyT and polyA like so:
sub polyT {
my ($dna) = @_;

return DNAappend($dna, 'TTTTTTTT');


}
sub polyA {
my ($dna) = @_;

return DNAappend($dna, 'AAAAAAAA');


}
Modules and Libraries

In my projects, I gather subroutine definitions into separate files called libraries, or modules,
which let me collect subroutine definitions for use in other programs. Then, instead of
copying the subroutine definitions into the new program (and introducing the potential for
inaccurate copies or for alternate versions proliferating), I can just insert the name of the
library or module into a program, and all the subroutines are available in their original
unaltered form. This is an example of software reuse in action.

22
Namespaces
A namespace is implemented as a table containing the names of the variables and subroutines
in a program. The table itself is called a symbol table and is used by the running program to
keep track of variable values and subroutine definitions as the program evolves. A namespace
and a symbol table are essentially the same thing. A namespace exists under the hood for
many programs, especially those in which only one default namespace is used.

Large programs often accidentally use the same variable name for different variables in
different parts of the program. These identically named variables may unintentionally interact
with each other and cause serious, hard-to-find errors. This situation is called namespace
collision. Separate namespaces are one way to avoid namespace collision.

The package declaration described in the next section is one way to assign separate
namespaces to different parts of your code. It gives strong protection against accidentally
using a variable name that's used in another part of the program and having the two
identically-named variables interact in unwanted ways.

Box 2.6: Namespace

A namespace in computer science (sometimes also called a name scope) is an abstract


container or environment created to hold a logical grouping of unique identifiers or symbols
(i.e. names). An identifier defined in a namespace is associated only with that namespace.

Pilot Question 2.2


State the benefits of modularization on large and complex programs

23
Summary of Study Session 2
In this unit you have learnt the concept of modularity and the advantages derivable thereof.
A real-life example was illustrated considering electrical devices microwaves, electric
kettles, washers, dryers, etc. You also leant how to implement modular programming in
PERL programming language.

Abstraction is having a global view of the programming task at hand. It hides details of the
task. Abstraction has it costs and benefits. Functions and procedures are ways of splitting a
complex task into smaller units or modules. This makes room for easy design and
implementation a program.

24
GLOSSARY OF TERMS

Subroutines: Subroutines are small blocks of code in a modular program designed to


perform a particular task. Since a subroutine is in itself a small program, it can contain any of
the sequence , selection and iteration constructs.

Function: A function is simply a “chunk” of code that you can use over and over again,
rather than writing it out multiple times. Functions enable programmers to break down or
decompose a problem into smaller chunks, each of which performs a particular task.

Modular programming is a programming approach that allows programming task to be


chopped into smaller tasks or modules. This in turn makes the job easier and minimizes
occurrence of errors. It therefore becomes imperative for programmers to adopt this
approach when designing a program.

Abstraction is a programming principle that allows for the hiding of details of the task at
hand. Emphasis is on functionalities. In object oriented programming abstraction is
achieved via the combination of code and data into one container. The definition of both the
code and data together is a class. Class is a blue print for the production of objects.

25
Pilot Answers
Pilot Answer 2.1
 Ease of Use: This approach allows simplicity, as lines of program code can be
accessed in the form of modules, rather than focusing on the entire thousands and
millions of lines code. This allows ease in debugging the code and prone to less error.
 Reusability: It allows the user to reuse the functionality with a different interface
without typing the whole program again.
 Ease of Maintenance: It helps in less collision at the time of working on modules,
helping a team to work with proper collaboration while working on a large
application.

Pilot Answer 2.2


i. Abstraction is a fundamental concept in computer science and software engineering. It
refers to the process of simplifying complex systems by breaking them down into smaller,
more manageable components and hiding unnecessary details.

ii. Perl code to find the largest number of three


sub find_largest {
my ($num1, $num2, $num3) = @_;
my $largest = $num1;
if ($num2 > $largest) {
$largest = $num2;
}
if ($num3 > $largest) {
$largest = $num3;
}

return $largest;
}

# Example usage
my $result = find_largest(10, 5, 8);
print "The largest number is: $result\n";

26
Self-Assessment Questions (SAQs) for Study Session 2
i. State the benefits of modularization on large and complex programs
ii. What is Abstraction?
iii. Write a function to select the largest of 3 numbers

27
References/Further Reading

Fundamentals of Structured Programming, Lubia Vinhas, 2016 -


http://wiki.dpi.inpe.br/lib/exe/fetch.php?media=cap390:fund_prog12.pdf

Structured Programming with C++ by Kjell Backman, 2012 - https://tfetimes.com/wp-


content/uploads/2015/04/structured-programming-with-c-plus-plus.pdf

www.cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf -
https://cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf

Introduction to computer Science -


www.academia.edu/25814963/An_Introduction_to_Computer_Science

28
Study Session 3

Study Session 3: Elements of Structured Programming

Content
Introduction
Learning Outcomes for Study Session 3
Learning Activities
Unit 3.1: Overview of Structured Programming
3.1.1 Structured Programming Concept
3.1.2 Advantages of Structured Programming
3.1.3 Disadvantages of Structured Programming
Unit 3.2: Programming Language Paradigms
3.2.1 Imperative Paradigm
3.2.2 Functional Paradigm
3.2.3 Logical Paradigm
3.2.4 Object Oriented Paradigm
3.2.5 Other Paradigms
Summary for Study Session 3
Glossary of Terms
Pilot Answers
Self-Assessment Questions (SA Qs) for Study Session 3
References/Further Reading

29
Study Session 3: Elements of Structured Programming
Introduction
In structured programming design, programs are broken into different functions. These
functions are also known as modules, subprograms, subroutines or procedures. Structured
programming minimizes the chances of the function affecting another. It allows for clearer
programs code. It made global variables to disappear and replaced by the local variables.

A programming paradigm, or programming model, is an approach to programming a


computer based on a mathematical theory or a coherent set of principles. Examples of these
paradigms are imperative, functional, logical, object-oriented paradigms and others.

Learning Outcomes for Study Session 3


At the end of this study session, you should be able to:
3.1 State the advantages and disadvantages of structured programming and describe the
examples of programming paradigms.
3.2 State the various programming paradigms and describe each of the named
programming paradigms and programming languages associated with it.

30
Unit 3.1

3.1.1 Structured programming Concept


In structured programming design, programs are broken into different functions these
functions are also known as modules, subprogram, subroutines or procedures.
Each function is design to do a specific task with its own data and logic. Information can be
passed from one function to another function through parameters. A function can have local
data that cannot be accessed outside the function’s scope. The result of this process is that all
the other different functions are synthesized in another function. This function is known as
main function. Many of the high-level languages support structured programming.

Structured programming minimizes the chances of the function affecting another. It allows
for clearer programs code. It made global variables to disappear and replaced by the local
variables. Due to this change one can save the memory allocation space occupied by the
global variable. Its organization helps in the easy understanding of programming logic. So
that one can easily understand the logic behind the programs. It also helps the newcomers of
any industrial technology company to understand the programs created by their senior
workers of the industry.

Box 3.1: Programming Logic

Programming logic is a fundamental construct that's applied to computer science in a variety


of comprehensive ways. Programming logic involves logical operations on hard data that
works according to logical principles and quantifiable results.

In programming, there are several languages that supported Structured


programming, what are they?

The languages that support Structured programming approach are:


• PERL
• C
• C++

31
• Java
• C#
• Pascal

3.1.2 Advantages of Structured programming
• It is user friendly and easy to understand.
• Similar to English vocabulary of words and symbols.
• It is easier to learn.
• They require less time to write.
• They are easier to maintain.
• These are mainly problem oriented rather than machine based.
• Program written in a higher-level language can be translated into many machine
languages and therefore can run on any computer for which there exists an
appropriate translator.
• It is independent of machine on which it is used, i.e., programs developed in high
level languages can be run on any computer.

What are the disadvantages of structured programming


3.1.3 Disadvantages of Structured Programming
• Structured programming codes implemented in high-level language has to be
translated into the machine language by translator and thus a price in computer time
is paid.
• The object code generated by a translator might be inefficient compared to an
equivalent assembly language program.
• Data types are proceeds in many functions in a structured program. When changes
occur in those data types, the corresponding change must be made to every location
that acts on those data types within the program. This is really a very time consuming
task if the program is very large.
• In a structured program, each programmer is assigned to build a specific set of
functions and data types. Since different programmers handle separate functions that
have mutually shared data type, other programmers in the team must reflect the

32
changes in data types done by the programmer in data type handled. Otherwise, it
requires rewriting several functions.
Box 3.2: Object

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.

Pilot Questions 3.1


Describe how structured programming can lead to programming efficiency.

Unit 3.2

3.2.1 Programming paradigms


Solving a programming problem requires choosing the right concepts. All but the smallest
toy problems require different sets of concepts for different parts of the program. A
programming paradigm, or programming model, is an approach to programming a
computer based on a mathematical theory or a coherent set of principles. It is a way of
conceptualizing what it means to perform computation and how tasks to be carried out on the
computer should be structured and organized. Programming languages are used to realize
programming paradigms.

What are the examples of a programming paradigms

Examples of programming paradigms are: imperative, functional, logical, object-oriented.


Most popular languages are imperative and use structured programming techniques.
Structured programming techniques involve giving the code you write structures, these often
involve writing code in blocks such as sequence (code executed line by line), selection
(branching statements such as if..then..else, or case) and repetition (iterative statements such
as for, while, repeat, loop).

33
Box 3.3: Loop

In computer programming, a loop is a sequence of instruction s that is continually repeated


until a certain condition is reached. Typically, a certain process is done, such as getting an
item of data and changing it, and then some condition is checked such as whether a counter
has reached a prescribed number.

3.2.2 Imperative paradigm


This paradigm is based on the ideas of a Von Neummann architecture. A command has a
measurable effect on the program and the order of commands is important. First do this and
next do that. Its main characteristics are incremental change of the program state (variables)
as a function of time; execution of commands in an order governed by control structures; and
the use of procedures, abstractions of one or more actions, which can be called as a single
command. Examples: Fortran, Algol, Basic, C, Pascal.

3.3.3 Functional paradigm


This paradigm is based on mathematics and theory of functions. The values produced are
non-mutable and plays a minor role compared to imperative program. All computations are
done by applying functions with no side effects. Functions are firsts class citizens. Evaluate
an expression and use the resulting value for something. Example: Haskell.

3.2.4 Logical paradigm


The logic paradigm fits well when applied in problem domains that deal with the extraction
of knowledge from basic facts and relations. Is based on axioms, inference rules, and queries.
Program execution becomes a systematic search in a set of facts, making use of a set of
inference rules. Examples: Prolog and List.

3.2.5 Object-oriented paradigm


Data as well as operations are encapsulated in objects. Information hiding is used to protect
internal properties of an object. Objects interact by means of message passing. In most
object-oriented languages, objects are grouped in classes and classes are organized as
hierarchies.

Box 3.4: Encapsulation

Encapsulation describes bundling data and methods that work on that data within one unit,

34
like a class in Java. We often use this concept to hide an object’s internal representation or
state from the outside. This is called information hiding.

Examples: PERL, C++, Java.

3.2.6 Other Paradigms


Other paradigms include Visual paradigm, Constraint based paradigm, Aspect oriented
paradigm and Event-oriented paradigm.

Pilot Question 3.2


i. List the examples of object-oriented programming language

35
Summary for Study Session 3
In this session you have learnt some programming paradigms. These include Imperative,
Functional, Logical, Object-Oriented Paradigms etc. These Paradigms are briefly discussed.
The programming languages associated with these Paradigms are also discussed.

You also have learnt structured programming concept, Advantages and Disadvantages of
Structured programming. Some programming languages that support Structured
programming approach are also listed.

36
GLOSSARY OF TERMS
Programming Paradigm: A programming paradigm, or programming model, is an
approach to programming a computer based on a mathematical theory or a coherent set of
principles.

Structured Programming: Structured programming design allows a program to be


subdivided into different functions. These functions can also be called modules, subprogram,
subroutines and procedures. Each function performs a particular task. These functions are
logically combined to carry out the desired task.

37
Pilot Answers
Pilot Answer 3.1
Structured programming is a programming paradigm that emphasizes the use of structured
control flow constructs, such as loops, conditionals, and subroutines, to organize and manage
the execution of a program. This approach to programming can lead to improved
programming efficiency in several ways:
 Readability and Maintainability: Structured programming promotes the use of clear
and organized code structures, making programs easier to read, understand, and
modify.
 Modular Design: Structured programming encourages the decomposition of a
program into smaller, self-contained modules.
 Control Flow Clarity: Structured programming provides clear control flow constructs
like loops and conditionals that allow for straightforward expression of program logic.
 Debugging and Error Handling: The structured nature of the code in structured
programming aids in the identification and resolution of bugs and errors.
 Reusability and Scalability: Structured programming promotes code reusability and
scalability.
 Code Optimization: Structured programming techniques make it easier to analyze and
optimize code performance.

Pilot Answer 3.2


 C++
 C#
 Dart
 Java
 JavaScript
 Objective-C
 PHP
 Perl
 Python
 Ruby

38
Self-Assessment Question (SA Qs) for Study Session 3
1. Differentiate with examples, the difference between functional and object-oriented
programming paradigms.
2. Describe how structured programming can lead to programming efficiency.

39
References/Further Reading

Fundamentals of Structured Programming, Lubia Vinhas, 2016 -


http://wiki.dpi.inpe.br/lib/exe/fetch.php?media=cap390:fund_prog12.pdf

Structured Programming with C++ by Kjell Backman, 2012 - https://tfetimes.com/wp-


content/uploads/2015/04/structured-programming-with-c-plus-plus.pdf

www.cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf -
https://cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf

Introduction to computer Science -


www.academia.edu/25814963/An_Introduction_to_Computer_Science

40
Study Session 4

Study Session 4: Structured Programming with PERL

Content
Introduction
Learning Outcomes for Study Session 4
Learning Activities
Unit 4.1 Overview of PERL and PERL Program Design
4.1.1 PERL basics
4.1.2 Executing a PERL program (script)PERL Variables and Data Types
4.1.3 Naming Convention
4.1.4 Basic Operators
4.1.5 PERL Program Design
4.1.6 Hashes
4.1.7 I/O BASICS
Unit 4.2 Executing a PERL Program
4.2.1 PERL Unless
4.2.2 Pearl Loop
Summary for Study Session 4
Glossary of Terms
Pilot Answers
Self-Assessment Questions (SA Qs) for Study Session 4
References/Further Reading

41
Study Session 4: Structured Programming with PERL
PERL stands for “Practical Extraction and Reporting Language”. It is an interpreted
programming language. An interpreter runs through a program line by line and executes each
command. The code itself is platform independent. It is a scripting language i.e. it contain
series of commands that are interpreted one by one at runtime and it is used to give
instruction to other software such as web browser, server or standalone. It is best known for
text processing – dealing with files, strings and regular expression (good for string
processing). PERL are useful the following.
i. Tool for general system administration
ii. Processing textual or numerical data
iii. Database interconnectivity
iv. Common Gateway Interface (CGI/Web) programming
v. Driving other programs (FTP, Mail, WWW, OLE)

Control Structures can be considered as the building blocks of computer programs. They are
commands that enable a program to “take decisions”, following one path or another. A
program is usually not limited to a linear sequence of instructions since during its process it
may bifurcate, repeat code or bypass sections.

Learning Outcomes for Study Session 4


At the end of this study session, you should be able to:
4.1 Writing simple PERL programs to analyze data files ·
4.2 Understanding PERL programs written by others ·
4.3 Use PERL basic syntax and modules in PERL programming language
4.4 write a program using control structure.

42
Unit 4.1

4.1.1 PERL BASICS


The following are PERL basics:

1. A line of code is called statement

2. A block can contain several statements and enclosed in curly braces:

{ statement_1
statement_2 …
statement_n
}

3. All lines of code in PERL must end with one semicolon:

print "Hello.";

The only exception is a one-line statement enclosed in curly braces:

{ statement }

4. Comment lines are preceded with # symbol. The # can come at any point in the line:

Whatever comes after it will be ignored during execution:

# This next line sorts alphabetically statement; # this statement handles


computation

How to do execute Perl script?

4.1.2 Executing a PERL program (script)

PERL scripts can be executed in two ways:

1. Use command line (-e meaning \program follows as next argument")

> PERL -e "print 'Hello, World!'"

2. From a text file

Create a plain-text document with the following program code in a text editor:

43
#!/usr/bin/PERL print 'Hello,
World!';

Save the document as "myprogram.pl" and run it from the prompt as follows:

> PERL myprogram.pl Hello,


World!

PERL Variables and Data Types


A variables can be considered as a container which holds one or more values. Once defined,
the variable remains, but the value or values can change over and over again. The value(s)
can be numbers or strings data types. There are three types of variables, namely, scalar, array
and hash.
Scalars are variables that holds a single value. Scalar names begin with $:
Variable Value
$name = "Aisha";
$age = "20";

Array is a variable that holds multiple values in series. Array names begin with @:

@names = ("Howard", "Leslie", "Bob");

A hash is a variable that holds pairs of data. Hash names begin with %:

%traits = ("name" => "Howard", "age" => "30", "eyes" =>

"brown");

Variable names begin with the special type-indicating character ($, @, or %, respectively),
followed by any combination of letters, numbers, and underscores. The first character after
the $, etc. must be a letter or underscore, not a number. Note: Variable names are case-
sensitive. Some valid variable names are: $time_of_arrival, $Time_of_Arrival,
$timeofdeparture and $TOD.

Box 4.1: Scalar

A scalar is a single value that is not an array. A scalar may be string, integer, or a floating-
point. For example, "my $value="example";" is an example of a scalar in Perl, where $value
is equal to the string 'example'

44
Box 4.2: Hash

Hashing is the process of transforming any given key or a string of characters into another
value. This is usually represented by a shorter, fixed-length value or key that represents and
makes it easier to find or employ the original string.

What are the rules for naming Scalars


4.1.3 Naming Convention
There are certain rules about naming variables. PERL has the following rules for naming
scalars:

1. All variable names will begin with a $, @ or %.

2. After the first character, alphanumeric characters i.e., a to z, A to Z and 0 to 9 are


allowed. Underscore is also allowed. Use underscore to split the variable names into two
words. But the first character cannot be a number.

3. Examples:

Legal variable Non-legal


names variable names
$var; mohohoh
$var_1; missing
@array; $47
%my_hash; %
4. Some variables have a predefined and special meaning to PERL. A few of the most
commonly used ones are listed below.

$_ The default input and pattern-searching space


$0 Program name
$$ Current process ID
$! Current value of errno
@ARGV Array containing command-line arguments for the script
@INC The array containing the list of places to look for PERL
scripts to be evaluated by the do, require, or use constructs
%ENV The hash containing the current environment

45
%SIG The hash used to set signal handlers for various signals

SCALARS

Scalars are simple variables that are either numbers or strings of characters. Scalar variable
names begin with a dollar sign followed by a letter, then possibly more letters, digits, or
underscores. Variable names are case-sensitive. Two type of scalar data types are:

1. Numbers

2. Strings

Numbers

This type of scalar data is of two types:

1. integers, singly its whole numbers, like 3, 0, 490

2. floating point numbers i.e. real numbers, like 3.14, 0.333, 6.74

Strings

Strings are simply sequences of characters. There are two different types of strings:

1. single quotes string literals

2. double quotes string literals

Single-quoted string literals

Single quotation marks are used to enclose data you want to be taken literally. Example are:

#!/usr/bin/PERL
$num = 7;
$txt = ‘it is $num’; print $txt;
Output it is $num

Double-quoted string literals

Double quotation marks are used to enclose data that needs to be interpolated before
processing. That means that escaped characters and variables aren’t simply literally inserted

46
into later operations, but are evaluated on the spot. Escape characters can be used to insert
newlines, tabs etc.

$num = 7;
$txt = “it is $num”; print $txt;
Output: it is 7

Here due to double quotes values of $num is taken added to the value of $txt. Double-quotes
interpolate scalar and array variables, but not hashes. On the other hand, you can use double
quotes to interpolate slices of both arrays and hashes.

Below is a list of common backslash escapes used for interpolating:

\n Newline

\r Carriage return

\t Tab

\b Backspace

\e Escape \\
Backslash

\” Double quote

\’ Single quote \l
lowercase next letter

\u uppercase next letter

4.1.4 Basic Operators


Arithmetic
Example Name Result
$a + $b Addition Sum of $a and $b
$a * $b Multiplication Product of $a and $b
$a % $b Modulus Remainder of $a divided by $b $a **
$b Exponentiation $a to the power of $b

47
String
Example Name Result
$a . “string” Concatenation String built from pieces
“$a string” Interpolation String incorporating the value of $a
$a x $b Repeat String in which $a is repeated $b times

Box 4.3: Operator

An operator is a character or characters that determine the action that is to be performed or


considered. There are three types of operator that programmers use: arithmetic operators,
relational operators and logical operators

Assignments Operator

The basic assignment operator is “=”: $a = $b.

PERL conforms to the C idiom that:

variable operator = expression is


equivalent to

variable = variable operator expression

So that $a += $b is equivalent to $a = $a + $b

$a -= $b $a = $a - $b
$a *= $b $a = $a * $b
$a /= $b $a = $a / $b
$a %= $b $a = $a % $b

This also works for the string concatenation operator: $a.= “\n”

The autoincrement and autodecrement operators are special cases of the assignment
operators, which add or subtract 1 from the value of a variable:

++$a, $a++ Autoincrement Add 1 to $a


--$a, $a-- Autodecrement Subtract 1 from $a

48
Logical Operators

Conditions for truth:

Any string is true except for “” and “0”


Any number is true except for 0
Any reference is true
Any undefined value is false
Example Name Result
$a && $b And True if both $a and $b are true
$a || $b Or $a if $a is true; $b otherwise
!$a Not True if $a is not true
$a and $b And True if both $a and $b are true
$a or $b Or $a if $a is true; $b otherwise
not $a RelationalNot True if $a is not true
Operators
Relation Numeric String Result
Equal == eq True if $a equal to $b
Not equal != ne True if $a not equal to $b
Less than < lt True if $a less than $b
Greater than > gt True if $a greater than $b
Less than or equal <= le True if $a not greater than $b
Comparison <=> cmp 0 if $a and $b equal
1 if $a greater
-1 if $b greater

Examples

$limit = 100; $name =


"Eliani"; if ($number == 100)
{ print "Limit!"
}
$grade = ($grade * 30)/100;
$name = $first_name . " " . $last_name;

49
@grades = ("98", "84", "73", "89"); print "$grades[0]
and $grades[2]"; @VOTs = ("400", "378", "352");
print @VOTs; 400378352 print "@VOTs"; 400 378
352
print '@VOTs'; # to review
@VOTs print "Name:\tBecky\nEyes:\thazel\n";

Name: Becky
Eyes: hazel $name =
"Alejna";

print "Hello, $name!\n";


Result: Hello, Alejna!
Scope of variables – Access Modifiers
We can declare a scalar in anywhere in the program. But you need to specify an access
modifier. Three types of modifiers are:

1. my

2. local

3. our

Use my to declare any variable which is specific within a block i.e. within the curly braces.

#!/bin/PERL my
$var=5;
if(i) {
my $var_2=$var;
} print $var_2;

The output of the program will be nothing. In the example, two variables are declared, one
inside if block ($var_2) and the other outside the if block ($var). The variable declared
outside the block will be accessible to if block but the variable which was declared inside if
block won’t be accessible to the outer program.
The local modifier mask the same variable values to different values without actuaclly
changing the original values of the variable, suppose we have a variable $a for which the

50
value is assigned 5, you can actually change the vale of that variable by re-declaring the same
variable using local keyword without altering the original value of the variable which is 5 as
follows:

#!/bin/PERL my
$var=5;
{
Local $var = 3;
Print “local, \$var = $var \n”;
}
print “global, \$var = $var \n”;

The output of the above program will be:

local, $var = 3 global, $var = 5


This way we can change the value of the variable without affecting the original value. A
variable declared with access modifier “our” can be used across the entire package. The
variable can be accessed in any script which will use that package.

4.1.5 PERL Program


Design
Arrays

An array is a special type of variable which stores data in the form of a list; each element can
be accessed using the index number which will be unique for each and every element. You
can store numbers, strings, floating values, etc. in your array.

Defining Arrays
In PERL, you can define an array using ‘@’ character followed by the name that you want to
give.

Dynamic array

Dynamic arrays are those that you declare without specifying any value on them. We store
value in the array during runtime from string scalar variable using the split function. Two

51
ways it does this is split up on spaces or commas. . Example on split by spaces is given
below:

$sentence = "Sue and I split up."; @words = split(/ /,


$sentence); print "$words[4]\n"
The split on commas example:

$list = "Eenie, meenie, miney, moe"; @words =


split(/,/, $list); print "$words[3]\n";

Counting Array Element (Array size)

The scalar function is a method of counting the elements in an array.

@people = ("Moe", "Larry", "Curly"); print scalar(@people).


"\n";
3

The second method of counting elements in

$count = @people; print


"$count\n";
3

The third method gives the last index of an array as follows:

print "$#people";
2

Sorting array elements

You can sort the elements of an array or the keys of a hash with the function sort. Note: By
default, it sorts both strings and numbers alphabetically!

@array = ("Betty", "Cathy", "Abby");


@array = sort(@array); print "@array\n";
Abby Betty Cathy
@array = ("3", "40", "24", "100");
@array = sort(@array); print "@array\n";
100 24 3 40

52
Sorting Array Keys

A very common type of loop makes use of the functions sort and keys. The latter yields all
the keys (not the values) in an array.

%signs = ("Frank" => "Capricorn", "Amanda" => "Scorpio"); foreach $person (sort
keys %signs) { print "$person: $signs{$person}\n";
}
Amanda: Scorpio
Frank: Capricorn

The reverse function reverses the order of the elements of a list

@b = reverse(@a);

Adding elements to arrays

There are two ways of adding new elements to existing arrays. If we know the index we want
the element to have, we can do this:

@numbers = ("210", "450", "333");


$numbers[3] = "990";

If we simply want to add an element to the end of an array, we can use push:

push(@numbers, "990");
210 450 333 990

Push, Pop, shift, unshift for PERL arrays

Many list-processing functions operate on the paradigm in which the list is a stack. The
highest subscript end of the list is the “top,” and the lowest is the bottom.

push Appends a value to the end of the list


push(@mylist,$newvalue)
pop Removes the last element from the list (and returns it)
pop(@mylist)
shift Removes the first element from the list (and returns it)
53
shift(@mylist)
unshift Prepends a value to the beginning of the list unshift(@mylist,$newvalue)
splice Inserts elements into a list at an arbitrary position
splice(@mylist,$offset,$replace,@newlist)

4.1.6 Hashes

A hash (or associative array) is an unordered set of key/value pairs whose elements are
indexed by their keys. Hash variable names have the form %foo.

A hash can also hold as many scalars as the array can hold. The only difference is that instead
of index we have keys and values. A hash contains an unordered set of key/value pairs whose
elements are indexed by their keys. A has can be declared starting with % followed by the
name of the hash.
Hash Variables and Literals

A literal representation of a hash is a list with an even number of elements (key/value


pairs) as described by the following examples:

%hash = (‘Femi’=>18, ‘Amina’=>17, ‘Chinedu’=>19);

Hash Functions

The keys’ function returns a list of all the current keys for the hash in question.

@hashkeys = keys(%hash);

As with all other built-in functions, the parentheses are optional:

@hashkeys = keys %hash;

In a scalar context, the keys’ function gives the number of elements in the hash. Conversely,
the values function returns a list of all current values of the argument hash:

@hashvals = values(%hash);

You can remove elements from a hash using the delete function:

delete $hash{‘key’};

54
4.1.8 I/O Basics

PERL needs data to interact with. Input refers to getting information into your program while
the output is the information obtained from a program.

Taking Inputs

The input from the keyboard (standard input) can be achieved as follows:

print “Please enter your name: “; my $input =


<STDIN>; print "\nhello $name!\n";

my $name declares a scalar variable. It can hold a number (integer or real), or an arbitrary
length string. <STDIN> means read one line from stdin. The line read is then assigned to
$name. The second print statement prints the result of the string "\nhello $name!\n" after
variable interpolation: the current value of $name is interpolated into the string in place of the
character sequence $name. For instance, if $name = "Kola" then the string would be "\nhello
Kola!\n". The < > operator reads a line and returns it including the newline (\n) at the end. To
get rid of these new line use chomp as follows:

chomp $name; immediately after reading $name. This


deletes a trailing newline.

Writing Output

The output is displayed using print function. The print function can take any number of
arguments and prints them to the standard output (usually the screen).

print “Hello World!\n”;


$a=4; print “$a”;

Pilot Question 4.1


1. Length function : Use the function length to find to length in characters of a scalar.
$string = "abcdefghij"; $howbig =
length($string); print
"$howbig\n";
10

2. Write a program to create an Array , sort the array element and add values to the array.

55
Unit 4.2

Conditional Structures (If/elsif/else)

The basic construction to execute blocks of statements is the if statement. The if statement
permits execution of the associated statement block if the test expression evaluates as true. It
is important to note that unlike many compiled languages, it is necessary to enclose the
statement block in curly braces, even if only one statement is to be executed.

The general form of an if/then/else type of control statement is as follows:

if (expression_one) { true_one_statement;
} elsif (expression_two) { true_two_statement;
} else { all_false_statement;
}

Example 4.5

The “ternary” operator is another nifty one to keep in your bag of tricks:

$var = (expression) ? true_value : false_value;


It is equivalent to:
if (expression) {
$var = true_value;
} else {
$var = false_value;
}

4.2.1 PERL Unless


Unless is opposite to if, unless code block will be executed if the condition is false.

my $a = 5;
unless ($a==5)
{
56
print “inside the unless block – The value is $a”;
}
else
{
print “Inside else block --- The value is $a”;
}
Output:

Inside else block – The value is 5

4.2.2 Pearl Loop

Loop statements are used to repeat the executing of some code. PERL supports four types of
control structures (similar to other programming languages) for, foreach, while and until.
PERL provides several different means of repetitively executing blocks of statements.

For loop
The code block will execute till the condition is satisfied. The for loop has three semicolon
separated expressions within its parentheses. These expressions function respectively for the
initialization, the condition, and incrementing as shown below:

for (initialization; condition; incrementing) { statements;


}
This structure is typically used to iterate over a range of values. The loop runs until the
condition is false.

for ($i; $i<10;$i++) { print $i;


}

Box 4.4: Conditions

Conditions are a key part of programming, but are also something that you probably use
every day without thinking about it. A condition is a statement that can be either true or false,
and programmers can use conditions to trigger actions.

Foreach

57
The foreach statement is much like the for statement except it loops over the elements of
a list:

my @array = (1..5); foreach $i (@array) { print “The


value is $value\n";
}
Output
The value is 1
The value is 2
The value is 3
The value is 4
The value is 5

If the scalar loop variable is omitted, $_ is used as follows:

my @array = (1..5); foreach (@array) { print “The value is $_\n";#This is same as the
above #code
}

Output
The value is 1
The value is 2
The value is 3
The value is 4
The value is 5
We can obtain hash keys and values using foreach as follows:

my %hash = (‘Tom’ => 23, ‘Jerry’ => 24, ‘Mickey’ => 25); foreach my $key (keys
%hash) { print “$key \n";
}

Output
Mickey
Tom
Jerry

58
While
The PERL while loop is a control structure, where the code block will be executed till the
condition is true. The code block will exit only if the condition is false. Example is as
follows:

#!/usr/bin/PERL $a=1;
while ($a<3) { print “$a\n”;
$a=$a+1;
}
Output
1
2
3

Do-while
Do while loop will execute at least once even if the condition in the while section is false.

Foe example:

#!/usr/bin/PERL $a=1; do {
print “$a\n”; $a=$a+1;
}
while ($a<=3)
print “Now value is greater than 3”;
Output
1
2
3

Now value is greater than 3

It is possible to exit the loop before the end of the loop via three methods: next, redo, and last
statements.

59
next means "skip over everything else in the block, increment the counter, and
evaluate the conditional again."
redo means "skip over everything else in the block and evaluate the conditional again,
without incrementing the counter."

last means "exit the block and never come back." Example:

foreach $student (@students) { if ($student eq


"END_REGISTERED") { last;
}
elsif ($student eq "Silber"){ next; } else {
$grade = Check_Grade ($student);
} print "$student: $grade\n";
}

Pilot Question 4.2


1. Differentiate between a for loop and while loop.

2. Write a simple program to determine student grade in CSC 205 course

60
Summary of Study Session 4
In this study session, you have learnt Selection (if Statement, else-if Statement, else), iterative
(while statement, do-while loop, for loop). You have also learnt that:
 A variable can be considered as a container which holds one or more values. Once
defined, the variable remains, but the value or values can change over and over again.
 Scalars are simple variables that are either numbers or strings of characters.
 Scalar variable names begin with a dollar sign followed by a letter, then possibly
more letters, digits, or underscores. Variable names are case-sensitive.
 An array is a special type of variable which stores data in the form of a list; each
element can be accessed using the index number which will be unique for each and
every element. You can store numbers, strings, floating values, etc. in your array.
 A hash (or associative array) is an unordered set of key/value pairs whose elements
are indexed by their keys.
 PERL needs data to interact with. Input refers to getting information into your
program while the output is the information obtained from a program.
 The output is displayed using print function. The print function can take any number
of arguments and prints them to the standard output (usually the screen).

61
GLOSSARY OF TERMS
PERL: PERL programming language has control structures which make PERL qualify as a
structured programming language. These structures include sequence, selection and repetition
structure.
ARRAY: a number of mathematical elements arranged in rows and columns. (2) : a data
structure in which similar elements of data are arranged in a table

VARIABLE: In programming, a variable is a value that can change, depending on


conditions or on information passed to the program. Typically, a program consists of
instruction s that tell the computer what to do and data that the program uses when it is
running.

62
Pilot Answers

Pilot Answer 4.1


1. In this specific case, the string assigned to the variable $string is "abcdefghij". The
length() function is then used to calculate the length of the string, and the result is stored in
the variable $howbig. Finally, the value of $howbig is printed, which is 10 in this case,
representing the length of the string "abcdefghij".
This indicates that the length of the string "abcdefghij" is 10 characters.

2.
# Create an empty array
array = []

# Function to add a value to the array


def add_value(value):
array.append(value)
print("Value added successfully!")

# Function to sort the array


def sort_array():
array.sort()
print("Array sorted successfully!")

# Main program loop


while True:
print("\n--- Array Manipulation ---")
print("1. Add a value")
print("2. Sort the array")
print("3. Print the array")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
value = input("Enter the value to add: ")

63
add_value(value)
elif choice == '2':
sort_array()
elif choice == '3':
print("Array:", array)
elif choice == '4':
print("Exiting the program...")
break
else:
print("Invalid choice. Please try again.")

This program provides a menu-driven interface where you can choose to add a value to the
array, sort the array, print the array, or exit the program. The array is initially empty, and you
can add values to it using the add_value() function, which appends the provided value to the
array. The sort_array() function sorts the elements in the array using the built-in sort()
method. The sorted array can be printed using the "Print the array" option.

Pilot Answer 4.2


1. Loop is suitable when the number of iterations is known or when iterating over a
sequence, while the while loop is more appropriate when the number of iterations is not
predetermined or when you want to repeat a block of code until a specific condition is met.
The for loop provides a concise syntax for iterating over sequences, while the while loop
offers more flexibility in controlling the loop based on dynamic conditions.

2.
# Function to calculate the grade based on the score
def calculate_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
64
return "D"
else:
return "F"

# Main program
score = float(input("Enter the student's score: "))

grade = calculate_grade(score)

print("Student's grade:", grade)

In this program, the user is prompted to enter the student's score in the CSC 205 course. The
calculate_grade() function takes the score as an input and determines the corresponding grade
based on the following criteria:

A score of 90 or above receives an "A" grade.


A score between 80 and 89 receives a "B" grade.
A score between 70 and 79 receives a "C" grade.
A score between 60 and 69 receives a "D" grade.
Any score below 60 receives an "F" grade.
The calculated grade is then displayed to the user.

65
Self-Assesment Question (SAQs) for Study Session 4
1. The foreach statement is much like the for statement except it loops over the
elements of a list:

my @array = (5..10); foreach $i (@array) { print


“The value is $value\n";
}
Write out the output of the program above.
2. Write a program using until, do while loop, While, tests in an expression
3. Write the PERL scripts in a text editor such as Notepad. The first line of a PERL
program should begin with the following Hash-bangs or shebangs
4. From a text file
Create a plain-text document with the following program code in a text editor

5. Use the function length to find to length in characters of a scalar.

66
References/Further Reading

Fundamentals of Structured Programming, Lubia Vinhas, 2016 -


http://wiki.dpi.inpe.br/lib/exe/fetch.php?media=cap390:fund_prog12.pdf

Structured Programming with C++ by Kjell Backman, 2012 - https://tfetimes.com/wp-


content/uploads/2015/04/structured-programming-with-c-plus-plus.pdf

www.cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf -
https://cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf

Introduction to computer Science -


www.academia.edu/25814963/An_Introduction_to_Computer_Science

67
Study Session 5

Study Session 5: Introduction to PERL Programming Language

Content
Introduction
Learning Outcomes
Learning Activities
Unit 5.1: Subroutines and Functions
5.1.1 Invoking subroutines.
5.1.2 Passing arguments
5.1.3 Variable Scope
5.1.4 Regular Expressions
5.1.5 Character Classes
5.1.6 Special Variables
5.1.7 Regular Expression Operators
5.1.8 Split operator
5.1.9 Join operator
Unit 5.2: Pattern Matching
5.2.1 Grouping features
5.2.2 Anchoring Pattern
5.2.3 Alternation and bracketing patterns
5.2.4 RE special characters
5.2.5 Square bracket
5.2.6 File handles
5.2.7 Manipulating Files & Directories
Summary for Study Session5
Glossary of Terms
Pilot Answers
Self-Assessment Questions (SA Qs) for Study Session 5
References/Further Reading

68
Study Session 5: Introduction to PERL Programming Language

Introduction
PERL has the ability to make subroutines, which are user-defined functions. These lets you
recycle one chunk of code many times in one program. The name of a subroutine is another
PERL identifier (letters, digits, and underscores, but they can’t start with a digit) with a
sometimes-optional ampersand (&) in front
Regular expressions aren’t merely part of PERL; they’re also found in sed and awk, procmail,
grep, most programmers’ text editors such as vi and emacs, and even in more esoteric places.
If you’ve seen some of these already, you’re ahead of the game. Keep watching, and you’ll
see many more tools that use or support regular expressions, such as search engines on the
Web, email clients, and others.

Learning Outcomes for study session 5


At the end of this unit, student should be able to
5.1 define subroutines and functions in their programming.
5.2 create regular expression in PERL at the end of this unit.

69
Unit 5.1

PERL subroutines encapsulate blocks of code in the usual way. A subroutine can return a
scalar or an array. Subroutines are defined in PERL as:
sub subname { statement_1;
statement_2;
}
Subroutine definitions are global; there are no local subroutines.
To define your own subroutine, use the keyword sub, the name of the subroutine (without the
ampersand), then the block of code in curly braces which makes up the body of the
subroutine. Something like this:
sub marine
{ $n += 1;
# Global variable $n
print "Hello, sailor number $n!\n";
}

How can you invoke subroutines

5.1.1 Invoking subroutines

The ampersand (&) is the identifier used to call subroutines. They may also be called by
appended parentheses to the subroutine name:

name(); &name;

You may use the explicit return statement to return a value and leave the subroutine at any
point.

sub myfunc { statement_1;


if (condition) return $val; statement_2;
return $val;
}

70
You invoke a subroutine from within an expression by using the subroutine name
(with the ampersand):‖
&marine; # says Hello, sailor number 1!
&marine; # says Hello, sailor number 2!
&marine; # says Hello, sailor number 3!
&marine; # says Hello, sailor number 4!
Most often, you refer to the invocation as simply calling the subroutine
Return Value
You always invoke a subroutine as part of an expression, even if you don’t use the
result of the expression. When you invoked &marine earlier, you were calculating the
value of the expression containing the invocation, but then throwing away the result.
 Unless your subroutine is being particularly tricky and declares a “prototype,”
which dictates how a compiler will parse and interpret its invocation
arguments. This is rare—see the PERL sub documentation for more
information.
 If you wish to be powerfully tricky, read the PERL documentation about
coderefs stored in private (lexical) variables.

Box 5.1: Subroutine

A subroutine is a named block of code within a program that performs a specific task. It is
designed to be reusable and can be called multiple times from different parts of the program.

5.1.2 Passing arguments


Luckily, PERL has subroutine arguments. To pass an argument list to the subroutine, simply
place the list expression, in parentheses, after the subroutine invocation, like this:
$n = &max(10, 15); # This sub call has two parameters

PERL passes the list to the subroutine; that is, PERL makes the list available for the
subroutine to use however it needs to
Arguments to a subroutine are passed as a single, flat list of scalars, and return values are
passed the same way. Any arguments passed to a subroutine come in as @_. To pass lists of
hashes, it is necessary to pass references to them:

71
@returnlist = ref_conversion(\@inlist, \%inhash);

The subroutine will have to dereference the arguments in order to access the data values they
represent.

sub myfunc { my($inlistref,$inhashref) = @_;


my(@inlist) = @$inlistref; my(%inhash) =
%$inhashref; statements; return @result;
}

Prototypes allow you to design your subroutines to take arguments with constraints on
the number of parameters and types of data.

Example 5.1:

sub Three {
return (1 + 2);
}

$x = Three(); ## call to Three() returns 3 exit(0); ## exit the program


normally

5.1.3 Variable Scope

Any variables used in a subroutine that aren’t declared private are global variables. The my
function declares variables that are lexically scoped within the subroutine. This means that
they are private variables that only exist within the block or routine in which they are called.
The local function declares variables that are dynamic. This means that they have global
scope, but have temporary values within the subroutine. Most of the time, use my to localize
variables within a subroutine.

Example 5.2

sub Three { my ($x, $y); # declare vars $x and $y


$x = 1; $y = 2;
return ($x + $y);

72
}
# Variant of Three() which inits $x and $y with the array
#trick sub Three2 { my ($x, $y) = (1,
2);
return ($x + $y);
}

Private Variables in Subroutines

But if PERL can give you a new @_ for every invocation, can’t it give you variables
for your own use as well? Of course, it can. By default, all variables in PERL are
global variables; that is, they are accessible from every part of the program. But you
can create private variables called lexical variables at any time with my operator:

sub max {

my($m, $n); # new, private variables for this block

($m, $n) = @_; # give names to the parameters

if ($m > $n) { $m } else { $n }

These variables are private (or scoped) to the enclosing block; any other $m or $n is
totally unaffected by these two. And that goes the other way, too—no other code can
access or modify these private variables, by accident or design.

So, you could drop this subroutine into any PERL program in the world and know that
you wouldn’t mess up that program’s $m and $n (if any).

Box 5.2: Argument

An argument refers to a value that is passed to a subroutine or function when it is called. It


provides input or data for the subroutine to work with. Arguments can be variables, constants,
expressions, or other data structures.

73
@_ Parameters
PERL subroutines do not have formal named parameters like other languages. Instead, all the
parameters are passed in a single array called "@_". The elements in @_ actually point to the
original caller-side parameters, so the called function is responsible for making any copies.
Usually the subroutine will pull the values out of @_ and copy them to local variables. A
Sum() function which takes two numbers and adds them as follows:

sub Sum1 { my ($x, $y) = @_; # the first lines of many #functions look like this to
retrieve and name their
#params return($x + $y);
}
# Variant where you pull the values out of @_ directly
# This avoids copying the parameters sub Sum2 {
return($_[0] + $_[1]);
}
# How Sum() would really be written in PERL -- it takes
#an array of numbers of arbitrary length, and adds all of
#them...
sub Sum3 { my ($sum, $elem); # declare local vars
$sum = 0; foreach $elem (@_)
{ $sum += $elem;
} return($sum);

## Variant of above using shift instead of foreach sub sum4 { my ($sum,


$elem); $sum = 0;
while(defined($elem = shift(@_))) { $sum += $elem;
}
return($sum);
}

74
5.1.4 Regular Expressions

PERL's most famous strength is in string manipulation with regular expressions. A regular
expression is a way of describing a class of similar strings in a very compact pattern notation.

The simple syntax to search for a pattern in a string is:

$string =~ /pattern/) ## true if the pattern is found in the string

("binky" =~ /ink/) ==> TRUE

("binky" =~ /onk/) ==> FALSE

In the simplest case, the exact characters in the regular expression pattern must occur in the
string somewhere. All of the characters in the pattern must be matched, but the pattern does
not need to be right at the start or end of the string, and the pattern does not need to use all the
characters in the string.

A whole regex is (usually) placed inside a pair of `/' signs. Variables are interpolated before
pattern-matching occurs.

5.1.5 Character Classes


Square brackets can be used to represent a set of characters. For example [aeiouAEIOU] is a
one character pattern that matches a vowel. Most characters are not special inside a square
bracket and so can be used without a leading backslash (\). \w, \s, and \d work inside a
character class, and the dash (-) can be used to express a range of characters, so [a-z] matches
lowercase "a" through "z". So the \w code is equivalent to [a-zA-Z0-9]. If the first character
in a character class is a caret (^) the set is inverted, and matches all the characters not in the
given set. So [^0-9] matches all characters that are not digits. The parts of an email address
on either side of the "@" are made up of letters, numbers plus dots, underbars, and dashes. As
a character class that's just [\w._-].

"[email protected]" =~ m/^[\w._-]+@[\w._-]+$/

==> TRUE

75
5.1.6 Special Variables $1, $2, $3 …
If a =~ match expression is true, the special variables $1, $2, ... will be the substrings that
matched parts of the pattern in parenthesis -- $1 matches the first left parenthesis, $2 the
second left parenthesis, and so on. The following pattern picks out three words separated by
whitespace.

if ("this and that" =~ /(\w+)\s+(\w+)\s+(\w+)/) {

## if the above matches, $1=="this", $2=="and", $3=="that"


This is a nice way to parse a string -- write a regular expression for the pattern you expect
putting parenthesis around the parts you want to pull out. Only use $1, $2, etc. when the if =~
returns true. Other regular-expression systems use \1 and \2 instead of $1 $2, and PERL
supports that syntax as well. There are three other special variables: $& (dollar-ampersand) =
the matched string, $` (dollar-back-quote) = the string before what was matched, and $'
(dollarquote) = the string following what was matched.

The following loop rips through a string and pulls out all the email addresses. It demonstrates
using a character class, using $1 etc. to pull out parts of the match string, and using $' after
the match.

$str = 'blah blah [email protected], blah blah balh [email protected] blah


blah';

while ($str =~ /(([\w._-]+)\@([\w._-]+))/) { ## look for an email addr

print "user:$2 host:$3 all:$1\n"; ## parts of the addr

$str = $'; ## set the str to be the "rest" of the string

} output:

user:nick host:cs.stanford.edu all:[email protected] user:billg host:microsoft.com


all:[email protected]

Box 5.3: Regular Expressions

Regular expressions, often abbreviated as regex or regexp, are sequences of characters that
define a search pattern. They are widely used in programming and text processing to match
and manipulate strings based on specific patterns.

76
5.1.7 Regular Expression Operators
There are three regular expression operators within PERL:

1) Match Regular Expression - m//

2) Substitute Regular Expression - s///

3) Translation/Transliterate Regular Expression - tr/// or y///

The match operator, m//, is used to match a string or statement to a regular expression.

Example: A string and regular expression is matched, on success it returns “match found”
otherwise “match not found”.

#!/usr/bin/PERL
# Initializing a string
$a = "University";
# matching the string and a regular expression and
# returns match found or not if ($a =~ m/Uni/)
{
print "Match Found\n";
} else { print "Match Not Found\n";
}
Output

Match Found

The substitution operator, s///, is a variation of the match operator that is used to search and
replace. The basic form of the operator is −

s/PATTERN/REPLACEMENT/;

The PATTERN is the regular expression for the text that we are looking for. The
REPLACEMENT is a specification for the text or regular expression that we want to use to
replace the found text with. For example

#/user/bin/PERL

77
# Initialising a string

$string = "Adams is a computer science student.";

# Calling the substitute regular expression

$string =~ s/Adams/Sunday/;

$string =~ s/computer science/information science/;

# Printing the substituted string print "$string\n";

Output

Sunday is a information science student

The translation, tr/// or y///, is used to replace all the occurrences of a character with a given
single character.

The translation operators are −

tr/SEARCHLIST/REPLACEMENTLIST/
y/SEARCHLIST/REPLACEMENTLIST/

The translation replaces all occurrences of the characters in SEARCHLIST with the
corresponding characters in REPLACEMENTLIST.

Example:

#/user/bin/PERL

# Initialising a string
$string = 'Universities';

# Calling the tr/// operator

$string =~ tr/s/z/;

# Printing the replaced string print "$string\n";

Output

Univerzitiez

78
Standard PERL ranges can also be used, allowing you to specify ranges of characters either
by letter or numerical value.

$string =~ tr/a-z/A-Z/;

Box 5.4: Parameters

Parameters are variables defined within a subroutine or function that receive the values of the
arguments passed to the subroutine when it is called. They serve as placeholders for the input
values that will be used and manipulated within the subroutine.

What are split and Join Operators?


5.1.8 Split operator
Split looks for occurrences of a regular expression and breaks the input string at
those points.
@fields = split(pattern,$input);
Without any arguments, split breaks on the whitespace in $_:
@words = split; is equivalent to
@words = split(/\s+/,$_);

5.1.9 Join operator


Join, the complement of split, takes a list of values and glues them together with the provided
delimiting string.

$output = join($delimiter,@inlist);

Box 5.5: Character

In programming, a character refers to a single element of a character set, such as a letter,


digit, symbol, or whitespace. Characters are the fundamental building blocks used to
represent textual information in programming languages.

79
Pilot Question 5.1

1. Write a simple PERl program to calculate the variable length, calculate the minimum
and maximum value.

2. How do you stop your subroutine program right away in PERL?

Unit 5.2

Regular Expression Characters

A regex is made up of single character patterns, grouping patterns, alternation patterns,


anchoring patterns and bracketing patterns.

Single character

‘.’ matches any single character.

A single printable character matches itself [set] matches any single character in the set e.g.
For example, [aeiou] matches any single lowercase vowel. Also, the set may contain items of
the form a-f, which is a shorthand for abcdef.

For example, [a-z#%] matches any single lower-case letter, a hash-mark, or a percent sign. If
a set starts with a `^' character (eg. [^a-z#%]), the set is negated - the pattern matches any
character NOT in the set.

How can a programmer predefine useful character classes?

Several useful character classes are predefined.

Digit \d [0-9]
Non-digit \D [^0-9]
Words \w [a-zA-Z0-9_]
Non-word \W [^a-zA-Z0-9_]
Whitespace \s space or tab
Non-whitespace \S not space or tab

80
5.2.1 Grouping features

Sequence of single-character patterns: matches a corresponding sequence of characters.

eg. /[a-z]bc/ matches any lower case letter, followed immediately by a `b', followed
immediately by a `c', anywhere in the string.

Optional: `?' makes the previous pattern optional - i.e. match zero or one times. eg. /he?llo/
matches `hello' or `hllo'.

Zero-or-more: `*' makes the previous pattern apply any number of times (from 0 upwards).
eg. /he*llo/ matches `hllo', `hello', `heello' etc. It consumes the maximum number of `e's
possible (it's greedy).

One-or-more: `+' means match 1 or more times. eg. /he+llo/ matches `hello', `heello', `heeello'
etc but not `hllo'.
A regex can contain several of these operators: eg: /h[uea]*l+o/ matches `hlo', `hullo',
`hulllllo', `heeelo', `heuaueaaeuelllllllo' etc.

One problem with * and +, is that they are "greedy" -- they try to use up as many characters
as they can. Suppose you are trying to pick out all of the characters between two curly braces
{ }.

The simplest thing would be to use the pattern.

m/{(.*)}/ -- pick up all the characters between {}'s

The problem is that if you match against the string "{group 1} xx {group 2}", the * will
aggressively run right over the first } and match the second }. So $1 will be "group 1} xx
{group 2" instead of "group 1". Fortunately PERL has a nice solution to the too-aggressive-
*/+ problem. If a? immediately follows the * or +, then it tries to find the shortest repetition
which works instead of the longest. You need the ? variant most often when matching with .*
or \S* which can easily use up more than you had in mind. Use ".*?" to skip over stuff you
don't care about, but have something you do care about immediately to its right. Such as..

m/{(.*?)}/ ## pick up all the characters between {}'s, but stop

## at the first}

81
The old way to skip everything up until a certain character, say }, uses the [^}] construct like
this.

m/{([^}]*)}/ ## the inner [^}] matches any char except }

5.2.2 Anchoring Pattern

Placing `^' at the start of a regex matches the start of the string. Similarly, `$' at the end of a
regex matches the end of the string.

`\b' constrains the regex to match only at a word boundary.

Without any anchoring, the regex can match anywhere.

5.2.3 Alternation and bracketing patterns

A regex of the form /h[eua]*llo|wo+tcha/ matches either /h[eua]*llo/ or /wo+tcha/.

Note that /a|b|c|g/ should be written as /[abcg]/ instead for efficiency

Brackets may be placed around any complete sub-pattern, as a way of enforcing a desired
precedence. For example, in /so+ng|bla+ckbird/ obviously bird is only part of (bla+ckbird).

If you meant "/so+ng|bla+ck/ followed by /bird/", then write that as /(so+ng|bla+ck)bird/. If


you want a repetition of anything longer than a single character pattern, you need brackets, as
in /(hello)*/. Without brackets, /hello*/ means /hell/ followed by /o*/ of course!

Brackets have another useful side effect: they tell PERL's regex engine to remember or
capture the text fragment that matched the inner pattern for later reporting or reuse. eg:

my $str = "I'm a melodious little soooongbird, hear me sing";


print "found <$1>\n" if $str =~ /(so+ng|bla+ck)bird/;

After the match succeeds, the capture buffer variable $1 contains soooong - the part of $str
matching the bracketed regex.

Box 5.6: Pattern

In programming, a pattern refers to a specific arrangement or sequence of characters used to


match or search for similar sequences in text or data. Patterns can be defined using regular
expressions or other specialized syntax.

82
5.2.4 RE special characters

. # Any single character except a newline

^ # The beginning of the line or string

$ # The end of the line or string

* # Zero or more of the last character

+ # One or more of the last character

? # Zero or one of the last character

RE examples

^.*$ # matches the entire string hi.*bye #


matches from "hi" to "bye" inclusive x +y #
matches x, one or more blanks, and y ^Dear #
matches "Dear" only at beginning bags? #
matches "bag" or "bags" hiss+ # matches
"hiss", "hisss", "hissss", etc.

3.5 Square brackets

[qjk] # Either q or j or k

[^qjk] # Neither q nor j nor k

[a-z] # Anything from a to z inclusive

[^a-z] # No lower case letters

[a-zA-Z] # Any letter

[a-z]+ # Any non-zero sequence of

# lower case letters

More examples

[aeiou]+ # matches one or more vowels

83
[^aeiou]+ # matches one or more nonvowels

[0-9]+ # matches an unsigned integer

[0-9A-F] # matches a single hex digit

[a-zA-Z] # matches any letter

[a-zA-Z0-9_]+ # matches identifiers

More special characters

\n # A newline
\t # A tab

\w # Any alphanumeric; same as [a-zA-Z0-9_]

\W # Any non-word char; same as [^a-zA-Z0-9_]

\d # Any digit. The same as [0-9]

\D # Any non-digit. The same as [^0-9]

\s # Any whitespace character

\S # Any non-whitespace character

\b # A word boundary, outside [] only

\B # No word boundary

Quoting special characters

\| # Vertical bar

\[ # An open square bracket

\) # A closing parenthesis

\* # An asterisk

\^ # A carat symbol

84
\/ # A slash

\\ # A backslash

Alternatives and parentheses


jelly|cream # Either jelly or cream
(eg|le)gs # Either eggs or legs
(da)+ # Either da or dada or

# dadada or...

Regular Expression Examples


The following series gradually demonstrate each of the above control codes. Study them
carefully -- small details in regular expressions make a big difference. That's what makes
them powerful, but it makes them tricky as well.

#### Search for the pattern 'iiig' in the string 'piiig'


"piiig" =~ m/iiig/ ==> TRUE
#### The pattern may be anywhere inside the string
"piiig" =~ m/iii/ ==> TRUE
#### All of the pattern must match
"piiig" =~ m/iiii/ ==> FALSE
#### . = any char but \n
"piiig" =~ m/...ig/ ==> TRUE
"piiig" =~ m/p.i../ ==> TRUE
#### The last . in the pattern is not matched
"piiig" =~ m/p.i.../ ==> FALSE
#### \d = digit [0-9]
"p123g" =~ m/p\d\d\dg/ ==> TRUE
"p123g" =~ m/p\d\d\d\d/ ==> FALSE
#### \w = letter or digit
"p123g" =~ m/\w\w\w\w\w/ ==> TRUE
#### i+ = one or more i's

85
"piiig" =~ m/pi+g/ ==> TRUE
#### matches iii
"piiig" =~ m/i+/ ==> TRUE
"piiig" =~ m/p+i+g+/ ==> TRUE
"piiig" =~ m/p+g+/ ==> FALSE
#### i* = zero or more i's
"piiig" =~ m/pi*g/ ==> TRUE
"piiig" =~ m/p*i*g*/ ==> TRUE
#### X* can match zero X's
"piiig" =~ m/pi*X*g/ ==> TRUE
#### ^ = start, $ = end
"piiig" =~ m/^pi+g$/ ==> TRUE
#### i is not at the start
"piiig" =~ m/^i+g$/ ==> FALSE
#### i is not at the end
"piiig" =~ m/^pi+$/ ==> FALSE
"piiig" =~ m/^p.+g$/ ==> TRUE
"piiig" =~ m/^p.+$/ ==> TRUE
"piiig" =~ m/^.+$/ ==> TRUE
#### g is not at the start
"piiig" =~ m/^g.+$/ ==> FALSE
#### Needs at least one char after the g
"piiig" =~ m/g.+/ ==> FALSE
#### Needs at least zero chars after the g
"piiig" =~ m/g.*/ ==> TRUE
#### | = left or right expression
"cat" =~ m/^(cat|hat)$/ ==> TRUE
"hat" =~ m/^(cat|hat)$/ ==> TRUE
"cathatcatcat" =~ m/^(cat|hat)+$/ ==> TRUE
"cathatcatcat" =~ m/^(c|a|t|h)+$/ ==> TRUE
"cathatcatcat" =~ m/^(c|a|t)+$/ ==> FALSE

86
#### Matches and stops at first 'cat'; does not get to
'catcat' on the right
"cathatcatcat" =~ m/(c|a|t)+/ ==> TRUE
#### ? = optional
"12121x2121x2" =~ m/^(1x?2)+$/ ==> TRUE "aaaxbbbabaxbb" =~ m/^(a+x?b+)+$/ ==>
TRUE
"aaaxxbbb" =~ m/^(a+x?b+)+$/ ==> FALSE
#### Three words separated by spaces
"Easy does it" =~ m/^\w+\s+\w+\s+\w+$/ ==> TRUE
#### Just matches "gates@microsoft" -- \w does not match the
"."
"[email protected]" =~ m/\w+@\w+/ ==> TRUE
#### Add the .'s to get the whole thing
"[email protected]" =~ m/^(\w|\.)+@(\w|\.)+$/ ==> TRUE
#### words separated by commas and possibly spaces
"Klaatu, barada,nikto" =~ m/^\w+(,\s*\w+)*$/ ==> TRUE

PERL And Operating System Files and I/O

5.2.6 Filehandles

Variables which represent files are called "file handles", and they are handled differently
from other variables. They do not begin with any special character -- they are just plain
words. By convention, file handle variables are written in all upper case, like FILE_OUT or
SOCK. The file handles are all in a global namespace, so you cannot allocate them locally
like other variables. File handles can be passed from one routine to another like strings. Every
PERL program has three filehandles that are automatically opened for it: STDIN, STDOUT,
and STDERR:

STDIN Standard input (keyboard or file)

STDOUT Standard output (print and write send output here)

STDERR Standard error (channel for diagnostic output)

87
Box 5.7: Classes

In object-oriented programming (OOP), a class is a blueprint or a template for creating


objects. It defines a set of attributes (data) and methods (functions) that describe the behavior
and characteristics of the objects that will be created based on the class.

Open files
File handles are created using the open() function:

open(FILE,”filename”);

You can open files for reading, writing, or appending:

open(FILE,”> newout.dat”) Writing, creating a new file open(FILE,”>> oldout.dat”)


Appending to existing file open(FILE,”< input.dat”) Reading from existing file

As an aside, under Windows, there are a number of ways to refer to the full path to a file:

”c:\\temp\\file” Escape the backslash in double quotes


‘c:\temp\file’ Use proper path in single quotes
“c:/temp/file” UNIX-style forward slashes

It is important to realize that calls to the open() function are not always successful. PERL will
not (necessarily) complain about using a filehandle created from a failed open(). This is why
we test the condition of the open statement:

open(F,”< badfile.dat”) or die “open: $!”

Closing files
When you are finished using a filehandle, close it using close():

close(FILE);

88
Examples

Opening and closing files using file handle to a filename

## open "filename" for reading as file handle F1 open(F1, "filename");

## open "filename" for writing as file handle F2 open(F2, ">filename");


open(F3, ">>appendtome") ## open "appendtome" for appending

## close a file handle close(F1);

Creating a new file from an old file

$input_file = "bigoldfile.dat"; $output_file =


"output.txt"; open (INPUT, "$input_file"); open
(OUTPUT, ">$output_file"); while ($line =
<INPUT>) { print OUTPUT "$line";

} close (INPUT); close


(OUTPUT);

5.2.7 Manipulating Files & Directories


The action of opening a file for writing creates it. PERL also provides functions to
manipulate files without having to ask the operating system to do it. Open Directory

$filename = “C:\\Documents\\”;

opendir(DIR, filename)#DIR is the directory handler

Delete file/Directory

Delete an existing file. Unlink can take a list of files, or wildcard as an argument as well:
unlink(<*.bak>)

unlink(filename)

Rename directory

89
This function renames a file. It is possible to move files into other directories by specifying a
path as part of the new name.

rename(oldname, newname)

Create new directory

mkdir(dirname, mode)

The “mode” specifies the permissions (set this to 0777 to be safe).

Removes (empty) directories


rmdir(dirname)
Change current working directory to dirname

chdir(dirname)
Change the permissions of files/directories:

chmod(permission, list of files)


666 = read and write
444 = read only
777 = read, write, and executable
Modify timestamps on files or directories

utime(atime, mtime, list of files)


“atime” is the time of the most recent access, and “mtime” is the time the file/directory was
last modified.
Pilot Question 5.2
1. Define the following in regular expression:\| \[ \) \* \^ \/ \\

2. State either true or false to the following regular expressions:


"piiig" =~ m/g.+/ ==>

"cat" =~ m/^(cat|hat)$/ ==>


"hat" =~ m/^(cat|hat)$/ ==>
"cathatcatcat" =~ m/^(cat|hat)+$/ ==>
"cathatcatcat" =~ m/^(c|a|t|h)+$/ ==> TRUE

90
Summary for Study Session 5
In this study session 5, you have learnt that:
a. The simplest thing would be to use the pattern.
m/{(.*)}/ -- pick up all the characters between {}'s

The problem is that if you match against the string "{group 1} xx {group 2}", the * will
aggressively run right over the first } and match the second }. So $1 will be "group 1} xx
{group 2" instead of "group 1". Fortunately PERL has a nice solution to the too-aggressive-
*/+ problem. If a? immediately follows the * or +, then it tries to find the shortest repetition
which works instead of the longest. You need the ? variant most often when matching with .*
or \S* which can easily use up more than you had in mind. Use ".*?" to skip over stuff you
don't care about, but have something you do care about immediately to its right.

b. There are three regular expression operators within PERL:


1) Match Regular Expression - m//
2) Substitute Regular Expression - s///
3) Translation/Transliterate Regular Expression - tr/// or y///
The match operator, m//, is used to match a string or statement to a regular expression

91
GLOSSARY OF TERMS
Subroutine: A subroutine is a named block of code within a program that performs a specific
task. It is designed to be reusable and can be called multiple times from different parts of the
program.
Argument: An argument refers to a value that is passed to a subroutine or function when it is
called. It provides input or data for the subroutine to work with. Arguments can be variables,
constants, expressions, or other data structures.
Parameters: Parameters are variables defined within a subroutine or function that receive the
values of the arguments passed to the subroutine when it is called. They serve as placeholders
for the input values that will be used and manipulated within the subroutine.
Regular Expressions: Regular expressions, often abbreviated as regex or regexp, are
sequences of characters that define a search pattern. They are widely used in programming
and text processing to match and manipulate strings based on specific patterns.
Classes: In object-oriented programming (OOP), a class is a blueprint or a template for
creating objects. It defines a set of attributes (data) and methods (functions) that describe the
behavior and characteristics of the objects that will be created based on the class.
Character: In programming, a character refers to a single element of a character set, such as
a letter, digit, symbol, or whitespace. Characters are the fundamental building blocks used to
represent textual information in programming languages.
Pattern: In programming, a pattern refers to a specific arrangement or sequence of characters
used to match or search for similar sequences in text or data. Patterns can be defined using
regular expressions or other specialized syntax.

92
Pilot Answers

Pilot Answer 5.1


1.
use strict;
use warnings;

# Array of variables
my @variables = (10, 5, 8, 3, 12);

# Calculate the length of the array


my $length = scalar @variables;

# Calculate the minimum value


my $min = min_value(@variables);

# Calculate the maximum value


my $max = max_value(@variables);

# Print the results


print "Variable Length: $length\n";
print "Minimum Value: $min\n";
print "Maximum Value: $max\n";

# Function to calculate the minimum value


sub min_value {
my $min = shift;
foreach my $val (@_) {
$min = $val if $val < $min;
}
return $min;
}

# Function to calculate the maximum value


sub max_value {
my $max = shift;
foreach my $val (@_) {
$max = $val if $val > $max;
}
return $max;
}

2.
To stop a Perl subroutine program right away, you can use the return statement. The return
statement allows you to exit the subroutine and return to the calling code immediately

93
Pilot Answer 5.2
1.
In regular expressions, certain characters have special meanings and need to be escaped to
match them literally. Here's the definition of the following characters within regular
expressions:
\|: The backslash \ is used to escape the vertical bar | character in a regular expression.
Normally, | is a metacharacter that denotes alternation, meaning it matches either the
expression on its left or the expression on its right. However, by preceding it with a backslash
\|, it is treated as a literal character and matches the vertical bar character itself.

\[: The backslash \ is used to escape the opening square bracket [ character in a regular
expression. Square brackets are used to define character classes in regular expressions,
allowing you to specify a set of characters to match. By preceding the opening square bracket
with a backslash \[, it is treated as a literal character and matches the opening square bracket
itself.

\): The backslash \ is used to escape the closing parenthesis ) character in a regular
expression. Parentheses are used for grouping and capturing in regular expressions. By
preceding the closing parenthesis with a backslash \), it is treated as a literal character and
matches the closing parenthesis itself.

\*: The backslash \ is used to escape the asterisk * character in a regular expression. The
asterisk is a metacharacter that denotes zero or more occurrences of the preceding element.
By preceding the asterisk with a backslash \*, it is treated as a literal character and matches
the asterisk itself.

\^: The backslash \ is used to escape the caret ^ character in a regular expression. The caret
has multiple meanings in regular expressions, depending on its position. Inside square
brackets, it negates the character class. At the beginning of a pattern, it denotes the start of a
line. By preceding the caret with a backslash \^, it is treated as a literal character and matches
the caret itself.

\/: The forward slash / character does not need to be escaped in a regular expression, as it
does not have any special meaning. It can be used directly to match a forward slash character.
94
\\: The backslash \ is used to escape itself in a regular expression. By preceding the backslash
with another backslash \\, it is treated as a literal character and matches the backslash itself.

2.
The regular expressions mentioned in the previous message can be evaluated as follows:

"piiig" =~ m/g.+/ matches the string "piiig" against the pattern g.+.
Result: TRUE (The pattern matches "piiig" as it starts with 'g' and has one or more characters
after that.)

"cat" =~ m/^(cat|hat)$/ matches the string "cat" against the pattern ^(cat|hat)$
Result: TRUE (The pattern matches "cat" as it is either "cat" or "hat" according to the
provided alternatives within the parentheses.)

"hat" =~ m/^(cat|hat)$/ matches the string "hat" against the pattern ^(cat|hat)$
Result: TRUE (The pattern matches "hat" as it is either "cat" or "hat" according to the
provided alternatives within the parentheses.)

"cathatcatcat" =~ m/^(cat|hat)+$/ matches the string "cathatcatcat" against the pattern


^(cat|hat)+$
Result: TRUE (The pattern matches "cathatcatcat" as it consists of one or more occurrences
of either "cat" or "hat" according to the provided alternatives within the parentheses.)

"cathatcatcat" =~ m/^(c|a|t|h)+$/ matches the string "cathatcatcat" against the pattern


^(c|a|t|h)+$
Result: TRUE (The pattern matches "cathatcatcat" as it consists of one or more occurrences
of either "c", "a", "t", or "h" according to the provided alternatives within the parentheses.)

95
Self-Assessment Questions (SA Qs) for Study Session 5
1. Make a program that prints each line of its input that contains a period (.), ignoring
other lines of input. Try it on the small text file from the previous exercise: does it
notice Mr. Slate?

2. Make a program that prints each line that has a word that is capitalized but not ALL
capitalized. Does it match Fred but neither fred nor FRED?

3. Make a program that prints each line that has a two of the same non-whitespace
characters next to each other. It should match lines that contain words such as
Mississippi, Bamm-Bamm, or llama.

4. Write a subroutine, called &above_average, which takes a list of numbers and returns
the ones which are above the average (mean). (Hint: make another subroutine that
calculates the average by dividing the total by the number of items.) Try your
subroutine in this test program.

5. Write a subroutine named greet that welcomes the person you name by telling them
the name of the last person it greeted
greet (“Fred" );
greet (“Barney" );
This sequence of statements should print: Hi Fred! You are the first one here! Hi
Barney! Fred is also here!

6. Modify the previous program to tell each new person the names of all the people it
has previously greeted:
greet( "Fred" );
greet( "Barney" );
greet( "Wilma" );
greet( "Betty" );

96
References/Further Reading

Fundamentals of Structured Programming, Lubia Vinhas, 2016 -


http://wiki.dpi.inpe.br/lib/exe/fetch.php?media=cap390:fund_prog12.pdf

Structured Programming with C++ by Kjell Backman, 2012 - https://tfetimes.com/wp-


content/uploads/2015/04/structured-programming-with-c-plus-plus.pdf

www.cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf -
https://cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf

Introduction to computer Science -


www.academia.edu/25814963/An_Introduction_to_Computer_Science

97
Study Session 6

Study Session 6: Operators and Control Statements

Content
Introduction
Learning Outcomes
Learning Activities
Unit 6.1: Modules and Database
6.1.1 Database and PERL
6.1.2 Database Drivers
6.1.3 PERL And Web Programming
6.1.4 Function-Oriented Script
Unit 6.2: Soap and Socket Programming
Summary for Study Session 6
Glossary of Terms
Pilot Answers
Self-Assessment Questions (SA Qs) for Study Session 6
References/Further Reading

98
Study Session 6: Operators and Control Statements

Introduction
Interacting with a database in PERL involves two pieces: the DBI and the database driver, or
DBD. Each of these pieces is a PERL module. The DBI provides the software interface that is
independent of the database, and the DBD provides the software that is database-dependent.
SOAP is a means by which remote procedures or methods can be called as if they were local.

Learning Outcomes for Study Session 6


At the end of this study session, you should be able to:
6.1 create and interact with databases in PERL programming language
6.2 have master the dynamics in the use of soap.

99
Unit 6.1

6.1.1 Database and PERL


Namespaces store identifiers for a package, including variables, subroutines, file handles, and
formats, so that they are distinct from those of another package. The default namespace for
the body of any PERL program is main. You can refer to the variables from another package
by “qualifying” them with the package name. To do this, place the name of the package
followed by two colons before the identifier’s name:

$Package::varname

If the package name is null, the main package is assumed.

Modules allow you to split a large program into separate source files and namespaces,
controlling the interface. They extend the functionality of core PERL with additional
compiled code and scripts. To make use of a package (if it’s installed on your system), call
the use function:

use CGI;

This will pull in the module’s subroutines and variables at compile time. PERL looks for
modules by searching the directories listed in @INC. Modules can be obtained from the
Comprehensive

PERL Archive Network (CPAN) at


http://www.cpan.org/modules/

or from the ActiveState site:

http://www.ActiveState.com/packages/zips/

To install modules under UNIX, unarchive the file containing the package, change into its
directory and type:

PERL Makefile.PL make


make install

100
On Windows, the ActivePERL distribution makes use of the “PERL Package Manager” to
install/remove/update packages. To install a package, run ppm on the .ppd file associated
with the module:

ppm install module.ppd

Interacting with a database in PERL involves two pieces: the DBI and the database driver, or
DBD. Each of these pieces is a PERL module. The DBI provides the software interface that is
independent of the database, and the DBD provides the software that is database-dependent.
Box 6.1: Database

A database is an organized collection of structured data that is stored and managed in a


computer system. It is designed to efficiently store, retrieve, and manipulate large amounts of
information.

What is DBI?
The DBI
The DBI (database independent/database interface), contains data-access libraries that are
independent of the type of database. The DBI provides a generic interface on which you call
a driver to access a database. This general interface allows you to use some common
methods, regardless of the backend database. The DBI is a module in itself, and thus is called
into your program’s namespace with a use pragma:

use DBI;

The DBI loads one or more database drivers (generally referred to as DBD, for database
dependent). The DBD, which will be discussed shortly, has the specific software and code
required to access a given type of database. It provides the interface between the DBI and the
type of database for the connection. When coupled with the appropriate DBD, the DBI is the
key to making database connections work.

6.1.2 Database Drivers


A database driver provides the database-interaction methods that are specific to the individual
database implementation. It is commonly referred to as the DBD, for database dependent,
since its code depends on which database is being used. For example, a MySQL database has
different syntax than an Oracle database. The DBI operates independently of the database,

101
leaving the implementation-specific bits to the DBD. You might be curious as to which
drivers are installed on your server. The DBI module provides a function for listing all of the
currently installed drivers. The example below uses the available_drivers() function of the
DBI module to retrieve the drivers available on the server.

#!/usr/bin/PERL use
strict; use DBI; my
@drivers;
@drivers = DBI->available_drivers(); foreach my $dbd
(@drivers) { print "$dbd driver is available\n";
} exit;
You run this program from the command line. The output will look something like this:

ExampleP driver is available Proxy driver is


available mysql driver is available

The program incorporates the DBI into the namespace with this line:

use DBI;

The available drivers are placed into an array called @drivers with this line:
@drivers = DBI->available_drivers;

Finally, the array is expanded within the foreach loop and printed to STDOUT, producing the
output. From the output, it is seen that MySQL DBD is installed on this server. If you wanted
to connect to a different type of database, you would need to obtain the DBD module from
your favorite CPAN mirror or install it from your distribution’s repository. For example,
Debian 3.0 includes a number of DBDs, a listing of which is available by searching the
repository with the command apt-cache search dbd.

What are the lists of some of the more popular DBDs we have?

1. MySQL: As previously stated, MySQL is one quarter of the prized LAMP (Linux-

Apache-MySQL-PERL) development platform that’s so popular around the world.

2. PostgreSQL: Another popular open-source database is PostgreSQL. The DBD for


PostgreSQL is similar to that of MySQL.

102
3. ODBC: The ODBC DBD is commonly used to connect to databases that run on
Windows systems, such as Microsoft SQL Server and Microsoft Access, but the
ODBC driver could be used to connect to virtually any database that offers ODBC
connectivity.

4. Sybase: Another popular DBD is used with the Sybase database server.

Box 6.2: SQL

SQL (Structured Query Language) is a programming language specifically designed for


managing and manipulating relational databases. It provides a standardized set of commands
and syntax for interacting with databases, allowing users to perform various operations such
as querying, inserting, updating, and deleting data.

6.1.3 PERL and Web Programming

CGI

CGI (Common Gateway Interface) is a standard of communication between a web server and
a client, such as a user with a web browser. CGI is a class of programs that work with web
servers. The programs themselves are considered to be external or separate from the web
servers, but they provide a gateway between the client and server and it provides a common
interface i.e. the CGI programs can be written in a number of languages. Of the languages
with which a CGI program can be written, PERL is arguably the most common.

6.1.4 Function-Oriented Script

The function-oriented method of CGI development allows you to rapidly develop small CGI
scripts. The function-oriented method requires that the developer explicitly call or import the
desired functions into their program. This is sometimes done by importing the method groups
rather than the individual methods themselves. The most common method grouping in
practice is the :standard group. This method group contains the most frequently used
methods, including those that make it easy to create and use of web forms, as well as the
HTML that surrounds those forms.

The :standard group is used in the Hello World example below:

#!/usr/bin/PERL -T use strict;

103
use CGI ':standard'; print
header;
print start_html('Hello World'); print h1('Hello
World'); print end_html(); exit;

Create this code in you’re a text editor and save it to a location defined to run CGI scripts
within your web server. For example, you can save the script as hello.cgi in the directory
/usr/lib/cgibin. The CGI will need the correct permissions in order to run. This can usually be
accomplished with the chmod 755 <scriptname.cgi> command:

chmod 755 /usr/lib/cgi-bin/hello.cgi

To view the code in a web browser, point the browser to the URL (uniform resource locator)
of the CGI script. For example, if the script is on a server at the IP address 192.168.1.10.
Combining the server address plus the aliased script location results in the following URL. If
all goes well, you should see a page similar to that in Figure below.

Figure 6.1: sample hello world page

104
From the example, it is seen that the standard invocation of the PERL interpreter
#!/usr/bin/PERL.
#!/usr/bin/PERL
The next line of code enables strict checking for the script: use
strict;
This line will show up in every script in this chapter. Following use strict; is the code that
actually calls the CGI.pm module, and more specific module.

use CGI ':standard';

Four functions of the CGI module are used in this script, as shown here:

print header;
print start_html('Hello World'); print h1('Hello
World'); print end_html();

The first function, header(), sends the Content-Type to the browser. In this instance, the
header() function is equivalent to using this bit of code in the script:

print "Content-Type: text/html\n\n";

The header() function can also be used for other HTTP headers, such as cookies. The next
CGI function used is start_html(). This function begins the HTML portion of the page with
elements like <title>, <html>, <head>, and so on. In this instance, the script calls the
start_html() function with a string parameter 'Hello World'. Another CGI function called in
this script is h1(). This function places an <h1> element around its parameter. In this case, the
parameter passed is 'Hello World', the phrase “Hello World” was indeed given <h1> size.
Finally, the end_html() function is called to provide the </body> and </html> closing tags.
The code in the example uses a semicolon (;) to end each line and then another print
statement to begin the next line. This was done to make the code easier to read. However, it’s
quite common to use a comma in place of the semicolon when programming a CGI
application, so the code would look like this:

#!/usr/bin/PERL -T use strict; use CGI


':standard'; print header,
start_html('Hello World'),

105
h1('Hello World'),
end_html(); exit;

Pilot Questions 6.1


1. State out the uniqueness of database in PERL programming language

Unit 6.2

6.2.1 PERL SOAP

SOAP is a ubiquitous protocol for exchanging information on the Internet. SOAP is a means
by which remote procedures or methods can be called as if they were local. When you call a
SOAP (Simple Object Access Protocol) method, you are requesting an application to perform
some computation and return a result to your program. This is the same concept as a local
method call; it’s just that the SOAP call happens to be remote. These method calls sent using
SOAP can be transported over a number of mechanisms, such as over HTTP. SOAP provides
a well-formed means to obtain information from a data source. In a SOAP request, you
provide parameters as required by the receiving application. These parameters are then used
by the server, which executes the query to the application’s data source on behalf of the client
and returns values to the client in a SOAP response. This information can then be parsed and
used within the local PERL application. The PERL SOAP::Lite module can be used to create
a SOAP client and a SOAP listener.

Box 6.3: SOAP

SOAP (Simple Object Access Protocol). SOAP is a means by which remote procedures or
methods can be called as if they were local.

SOAP is client/server format, with one side sending the message and the other side parsing
the XML content of the message. The application may take action based on the results of the
message, either on the receiver or sender, or both. SOAP is an XML format with three

106
elements: envelope, header, and body. The SOAP header and SOAP body are both contained
within the

SOAP envelope. The SOAP header is actually optional, although it’s almost always included.
The SOAP body contains the heart of the SOAP message. Several popular web sites have
SOAP interfaces available lists a select few of these services, along with a short description
of each. Some website with SOAP interface

Site/Service Description Information URL


Amazon.com Numerous web http://www.amazon.com/gp/aws/landing.html
services to expose
data on products at

Amazon.com
National Weather Web services to http://weather.gov/xml/
expose forecasts and
Service
conditions based on
latitude and
longitude; available
for U.S. locations
Google Interfaces to query http://www.google.com/apis/

Google’s directory
and more

6.2.2 Socket Programming

The socket is a medium through which two computers can interact on a network by using
network address and ports. To implement socket programing we need to create sockets in
both A(Server) and B (Client), A will be in the receiving state and B will be in the sending
state. The server wished to receive a connection from B(Client) and execute some tasks and
send the result back to B(Client). When we execute the code, the operation system in A tries
to create a socket and binds one port to that socket. Then it will listen from the sender which
is B. The client wishes to send some program from his system to A (Server) for some
processing. When we execute the code, the operating system in B tries to create a socket for
communicating with A (Server), B has to specify the IP address and the port number of A to

107
which B wishes to connect. If this goes well, both systems will interact to exchange the
information through one port. PERL also support socket programing. PERL has a native API
through which sockets can be implemented. To make it easy there are many CPAN modules
using which we write socket program. Server operations are:
1. Create socket
2. Bind socket with address and port
3. Listen to the socket on that port address
4. Accept the client connections which tries to connect using the port and IP of the
server
5. Perform operations
Box 6.4: Socket

The socket is a medium through which two computers can interact on a network by using
network address and ports.

Sockets PERL has full support for TCP/IP sockets, which means that you could write a web
server in PERL, or a web browser, Usenet news server or client, finger daemon or client, FTP
daemon or client, SMTP or POP or SOAP server or client, or either end of pretty much any
other kind of protocol in use on the Internet. You’ll find low-level modules for these in the
Net:: namespace, and many of them come with PERL.

Of course, there’s no need to get into the low-level details yourself; there are modules
available for all of the common protocols. For example, you can make a web server or client
with the LWP module and one or two lines of additional code.‖ The LWP module (actually, a
tightly integrated set of modules, which together implement nearly everything that happens
on the Web) is also a great example of high-quality PERL code, if you’d like to copy from
the best. For other protocols, search for a module with the protocol’s name.
Client Operations are:
1. Create Socket
2. Connect to Server using on its port address

Pilot Questions 6.2


1. List Server Operations
2. Differentiate between SOAP and FTP

108
Summary for Study Session 6
1. MySQL: As previously stated, MySQL is one quarter of the prized LAMP (Linux-

Apache-MySQL-PERL) development platform that’s so popular around the world.

2. PostgreSQL: Another popular open-source database is PostgreSQL. The DBD for


PostgreSQL is similar to that of MySQL.

3. ODBC: The ODBC DBD is commonly used to connect to databases that run on
Windows systems, such as Microsoft SQL Server and Microsoft Access, but the
ODBC driver could be used to connect to virtually any database that offers ODBC
connectivity.

4. Sybase: Another popular DBD is used with the Sybase database server.

The SOAP header is actually optional, although it is almost always included. The SOAP body
contains the heart of the SOAP message. Several popular web sites have SOAP interfaces
available. Make a list of a few of these services, along with a short description of each. You
can also identify some websites with SOAP interface.

109
Pilot Answers
Pilot Answer 6.1
Perl is a programming language known for its versatility and flexibility in handling various
tasks, including working with databases. When it comes to databases, Perl offers several
features that contribute to its uniqueness:
 Comprehensive Database Support: Perl provides comprehensive support for
connecting to and interacting with databases. It offers a wide range of database
modules and APIs (such as DBI, DBD::Oracle, DBD::MySQL, DBD::SQLite) that
allow Perl programs to connect to various database systems, including Oracle,
MySQL, SQLite, PostgreSQL, and more.
 CPAN Modules: Perl's Comprehensive Perl Archive Network (CPAN) is a vast
repository of modules contributed by the Perl community. CPAN hosts numerous
modules specifically designed for database connectivity, query execution, and
database management. These modules provide ready-to-use functionalities, making it
easier to work with databases in Perl.
 DBI (Database Interface): Perl's DBI module is a database-independent interface that
allows Perl programs to work with databases using a consistent API. It provides a
unified interface to connect to different database systems, execute queries, fetch
results, and manage transactions. DBI helps abstract the differences between database
systems, allowing developers to write portable database code.
 Flexible Database Integration: Perl's syntax and flexibility make it well-suited for
integrating with databases. Perl offers powerful text manipulation capabilities, regular
expressions, and native support for handling data structures such as arrays and hashes.
This enables developers to efficiently process and manipulate database results,
transform data, and build complex data structures from query outputs.
 Rapid Prototyping: Perl's concise and expressive syntax, combined with its database
integration capabilities, make it an excellent choice for rapid prototyping and scripting
tasks involving databases. Perl's ability to handle text processing, perform file I/O
operations, and interact with databases seamlessly makes it well-suited for tasks such
as data migration, data transformation, report generation, and automation of database-
related tasks.

110
Pilot Answer 6.2
1. Server operations refer to the various tasks and actions that can be performed on a
server. Here are some common server operations:
 Starting and stopping the server: This involves initiating the server software or
shutting it down gracefully.
 Configuring server settings: This includes modifying server configuration files to
customize the behavior and settings of the server.
 Managing user accounts and access: Creating, modifying, or deleting user accounts
and managing their permissions and access levels on the server.
 File management: Uploading, downloading, moving, copying, and deleting files and
directories on the server.
 Installing and updating software: Installing new software applications or updating
existing ones on the server.
 Monitoring server performance: Monitoring and analyzing server performance
metrics such as CPU usage, memory utilization, network traffic, etc.
 Handling security measures: Implementing security protocols, managing firewalls,
configuring SSL certificates, and ensuring server security.
 Handling backups and disaster recovery: Creating and managing backups of server
data to prevent data loss and implementing strategies for disaster recovery.
 Troubleshooting and debugging: Identifying and resolving server-related issues,
errors, or malfunctions.
 Managing network services: Configuring and managing various network services
such as DNS, DHCP, web server, email server, database server, etc.

2. SOAP is primarily used for communication and data exchange between web services,
while FTP is focused on file transfer between a client and a server. SOAP facilitates remote
procedure calls and structured data exchange, while FTP is designed specifically for file
management.

111
Self-Assessment Question (SAQs) for Study Session 6
1. State out the uniqueness of database in PERL programming language.
2. Write a simple function oriented script to calculate BMI of a named individual
3. List five websites, describe their information and URL.

112
References/Further Reading

Fundamentals of Structured Programming, Lubia Vinhas, 2016 -


http://wiki.dpi.inpe.br/lib/exe/fetch.php?media=cap390:fund_prog12.pdf

Structured Programming with C++ by Kjell Backman, 2012 - https://tfetimes.com/wp-


content/uploads/2015/04/structured-programming-with-c-plus-plus.pdf

www.cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf -
https://cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf

Introduction to computer Science -


www.academia.edu/25814963/An_Introduction_to_Computer_Science

113

You might also like