+ All Categories
Home > Documents > System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Date post: 21-Dec-2015
Category:
View: 219 times
Download: 2 times
Share this document with a friend
60
System Programming System Programming i i n n Operating Systems Operating Systems ITU ITU Informatics Institute Informatics Institute Dr. Serdar Çelebi Dr. Serdar Çelebi
Transcript
Page 1: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

System ProgrammingSystem Programmingiinn

Operating SystemsOperating Systems

ITU ITU Informatics InstituteInformatics Institute

Dr. Serdar ÇelebiDr. Serdar Çelebi

Page 2: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

• What is System Programing

• History of Perl

• Perl Basics– First Perl Program– Some Common Control Sequences– Arithmatic Operators– Control Structures I

Contents of first week

Page 3: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Introduction

What is System Programming? And what System Programmer do?

• ”System Programming" is a fairly loosely defined term which is generally used to refer to those programming tasks requiring direct interaction with the operating system; hardware. It is also used in reference to the implementation and maintenance of systems software e.g. the operating system itself; compilers; system utilities and communications software.

• A system programmer produced standalone general purpose utilities (e.g. editors, assemblers) and/or libraries of useful routines (e.g. graphics, mathematical). Often it involved building new services into the operating systems (e.g. new device drivers). The activity often required specialised knowledge of the underlying operating system and employed services not normally used by the applications programmer.

• The services and concepts that a real UNIX system programmer might employ are amenable to all programmers and are likely to be an element of an application program which needs to make efficient use of the available resources, i.e. multiple process creation, synchronisation of programs etc..

Page 4: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Introduction

• Shell Scripting• tcl & sed

• awk & gawk

• Python, Perl (Practical Extraction and Reporting Language)

Page 5: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Tcl & sed

• tcl (Tool Command Language)• Original design is centered around a macrolike

language for helping with shell-based applications (string handling). It is a true interpreter and good for embedding a scripting language inside another language. But it is not a general-purpose scripting language

• sed is a stream editing and filtering tool that complements awk

Page 6: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

awk & gawk

• awk and gawk are functionally subsets of Perl• awk was designed as a reporting language with the

emphasis on making the process of reporting via the shell significantly easier

• Perl built-in support (i.e. Network socket class), external file manipulation and management functions, many operating systems

• awk UNIX, simpler, smaller, more structured, much quicker for small programs, supports advanced regular expressions

Page 7: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Python

• Developed as an object-oriented language• General-purpose programming and good at

text processing• Unlike Perl, Python does not resemble C,

and it does not resemble Unix-style tools like awk. Resembles object oriented languages such as java

Page 8: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Perl (Practical Extraction and Reporting Language)

• Perl is particularly strong at:

Process, File and Text manipulation • This makes it espacially useful for:

System utilities, Software tools, System management tasks, Database access, Graphical programming, Networking, and World Wide Web programming

• These strengths make it particularly attractive to:

CGI script authors, system administrators, mathematicians, journalists, etc.

Page 9: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

History of Perl

• Developed by Larry Wall in 1987– Aimed to integrate features of the UNIX languages awk

and sed with framework provided by shell

• Gained support in open-source community

• Versions of Perl– Perl 3

• Adopted GNU General Public License

– Perl 4• Adopted Artistic License to attract more users, first “Camel”

book

– Perl 5• Major reorganization of Perl language

Page 10: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

History of Perl

– Perl 6• Development announced on July 18, 2000• A complete rewrite of internals and externals of Perl• More extensible with features such as threading, signal handling

and Unicode (a standard character set that can represent the majority of the world’s spoken language)

• Current release 5.8.8 (as of April 2006)

Page 11: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Perl Library

• Perl modules– Reusable pieces of software– Defined in library files ending in .pm– Primary distribution center is the Comprehensive Perl

Archive Network (CPAN). ( www.cpan.org )– To find and install modules on Windows (created by

ActiveState Tool Corporation) use the Perl Package Manager (PPM)

Page 12: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

General Notes About Perl

• Perl approach to programming– Qualities of a good programmer

• Laziness– Reusable code and applicable in as many places as possible

• Impatience– Do not do manually, Functional programs

• Hubris– Easy to understand code, readable code

– Programs can be written in many different ways. Love of freedom “There’s more than one way to do it”

– Highly portable (Operating Systems)

Page 13: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Some Internet Links

• http://www.perl.org• http://dev.perl.org

• http://www.cpan.org

• http://www.perl.com

• http://www.activestate.com

Page 14: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Possible Perl application topics

• Strings

• Numbers

• Dates and Times

• Arrays

• Hashes

• Pattern Matching

• File Access

• File Contents

• Directories

• Subroutines

• References and records

• Packages

• Libraries and Modules

• Classes

• Objects and Ties

• Database Access

• User Interfaces

• Process management

• Communication

• Sockets

• Internet services

• CGI programming, Web Automation

Page 15: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Unlike Perl 5, Perl 6 will provide• explicit strong typing

• proper parameter lists

• active metadata on values, variables, subroutines, and types

• declarative classes with strong encapsulation

• full OO exception handling

• support for the concurrent use of multiple versions of a module

• extensive introspection facilities (including of POD)

• LL and LR grammars (including a built-in grammar for Perl 6 itself)

• subroutine overloading

• multiple dispatch

• named arguments

• a built-in switch statement

• hierarchical construction and destruction

• distributive method dispatch

• method delegation

• named regexes

• overlapping and exhaustive regex matches within a string

Page 16: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Unlike Perl 5, Perl 6 will provide

• named captures

• parse-tree pruning

• incremental regex matching against input streams

• macros (that are implemented in Perl itself)

• user-definable operators (from the full Unicode set)

• chained comparisons

• a universally accessible aliasing mechanism

• lexical exporting (via a cleaner, declarative syntax)

• multimorphic equality tests

• state variables

• hypothetical variables

• hyperoperators (i.e. vector processing)

• function currying

• junctions (i.e. superpositional values, subroutines, and types)

• coroutines

Page 17: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Writing a Perl Program

Perl programs can be typed into a text editor program

(such as emacs or vi on UNIX, or Notepad on Windows)

and save the file as “program_name.pl”

Page 18: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Running Perl Program

#!/usr/bin/perl... Top of the file

user@machine:~ > ls -al first.pl-rwxr-xr-x 1 user users 56 May 27 14:37 first.pluser@machine:~ > ./first.plThis is my first perl Programuser@machine:~ >user@machine:~ >chmod u+x first.pl

x (executable)file

Extension is notimportant

#! Shebang construct

c:\perl\bin directory on MS#!c:\perl\bin\perl.exe

Page 19: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

user@machine:~ > ls -al first.pl-r--r--r-- 1 user users 56 May 27 14:37 first.pluser@machine:~ > perl first.plThis is my first perl Programuser@machine:~ > user@machine:~ > perl –e ‘print “Hello, World!\n”:’

• To compile a program and check for syntax errors, add the –ccommand-line option to the perl command (as in perl –c fileName.pl)

• The –e option tells Perl that there is a one-liner script coming up. The part just after the –e is the Perl code itself, inside single quotes (‘), or double quotes (“) for Windows.

perl compilation opcodes (operation codes) interpreter execution phase

Running Perl Program

Page 20: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

1 #!/usr/bin/perl

2 # Fig. 2.1: fig02_01.pl

3 # A first program in Perl

4

5 print "Welcome to Perl!\n"; # print greeting

Welcome to Perl!

The “shebang” construct (#!) indicates the path to the Perl interpreter on Unix and Linux systems.

The Perl comment character (#) indicates that everything on the current line following the # is a comment.

Function print outputs the string “Welcome to Perl!\n” to the screen.

The escape sequence \n represents newline and positions the screen cursor at the beginning of the next line.

; omitting the semicolon at the end of a statement is usually a syntax error

Page 21: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Escape Sequence Description

\n Newline. Position the screen cursor at the beginning of the next line.

\t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Position the screen cursor at the beginning of

the current line; do not advance to the next line.

\$ Dollar sign. Used to insert a dollar-sign character in a string. \\ Backslash. Used to insert a backslash character in a string. \" Double quote. Inserts a double-quote character in a double-quoted

string. \' Single quote. Inserts a single-quote character in a single-quoted

string. Some common escape sequences.

Page 22: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

1 #!/usr/bin/perl

2 # Fig. 2.3: fig02_03.pl

3 # Prints a welcome statement in a variety of ways

4

5 print ( "1. Welcome to Perl!\n" );

6 print "2. Welcome to Perl!\n" ;

7 print "3. Welcome ", "to ", "Perl!\n";

8 print "4. Welcome ";

9 print "to Perl!\n";

10 print "5. Welcome to Perl!\n";

11 print "6. Welcome\n to\n\n Perl!\n";

1. Welcome to Perl!2. Welcome to Perl!3. Welcome to Perl!4. Welcome to Perl!5. Welcome to Perl!6. Welcome to  Perl!

Arguments to built-in functions like print can be placed in parentheses.

Whitespace characters are ignored by Perl.

More than one argument may be passed to function print.

Although these statements are on separate lines, the string Welcome to Perl! is displayed on one line.

Newline characters may be used to print multiple lines of text using one line of code.

Page 23: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

1 #!/usr/bin/perl

2 # Fig. 2.4: fig02_04.pl

3 # A simple addition program

4

5 # prompt user for first number

6 print "Please enter first number:\n";

7 $number1 = <STDIN>;

8 chomp $number1; # remove "\n" from input

9

10 print "Please enter second number:\n";

11 $number2 = <STDIN>;

12 chomp $number2; # remove "\n" from input

13

14 $sum = $number1 + $number2;

15

16 print "The sum is $sum.\n";

Please enter first number:45Please enter second number:72The sum is 117.

Prompt to tell the user to enter the first number.

Declare scalar variable $number1.Assignment operator =.The expression <STDIN> causes program execution to pause while the computer waits for the user to enter data.

Function chomp removes the newline character from the end of the line.

The assignment statement calculates the sum of the variables $number1 and $number2 and assigns the result to variable $sum.

Page 24: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

$number1 45\n

$number1 45

Page 25: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

$number1

$number272

45

Page 26: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

$number1 45

$number2 72

$sum 117

Page 27: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

String scalar values•Single quoted ‘ ‘

•Double quoted “ “

•It interpolates variables (such as $sum) and escape sequences(such as \n) in the string.•Dollar sign ($) reminds that the variable refers to a scalar valueIn single quote, it interpolates only the escape sequences \’ and\\, for inserting single-quote characters and backslash charactersin the string.The following statement would output the string exactly as it appears between the single quotes:

print ‘The sum is $sum. \nThank you.’;

Page 28: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Operation Arithmetic operator Algebraic expression Perl expression

Addition + x + y $x + $y

Subtraction - x – y $x - $y Multiplication * xy $x * $y Division / x / y $x / $y

Modulus % x mod y $x % $y Exponentiation ** x y $x ** $y

Arithmetic operat ors.

Arithmetic Operators

Page 29: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Operator(s) Operation(s) Order of evaluation (precedence)

( ) Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.

** Exponentiation Evaluated second. If there is more than one, the operators are evaluated from right to left.

*, / or % Multiplication Division Modulus

Evaluated third. If there is more than one, the operators are evaluated from left to right.

+ or - Addition Subtraction

Evaluated last. If there is more than one, the operators are evaluated from left to right.

Precedence of arithmetic operators.

Precedence of Arithmetic Operators

Page 30: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Assignment operator Sample expression

Explanation Assigns

Assume that: $c = 3 , $d = 5 , $e = 4 , $f = 6 , $g = 12 and $h = 5 .

+= $c += 7 $c = $c + 7 10 to $c -= $d -= 4 $d = $d - 4 1 to $d *= $e *= 5 $e = $e * 5 20 to $e /= $f /= 3 $f = $f / 3 2 to $f %= $g %= 9 $g = $g % 9 3 to $g **= $h **= 2 $h = $h ** 2 25 to $h Arithmetic assignment operators.

Arithmetic Assignment Operators

Page 31: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Operator Name Sample expression

Explanation

++ preincrement ++$c Increment $c by 1, then use the new value of $c in the expression in which $c resides.

++ postincrement $c++ Use the current value of $c in the expression in which $c resides, then increme nt $c by 1.

-- predecrement --$d Decrement $d by 1, then use the new value of $d in the expression in which $d resides.

-- postdecrement $d-- Use the current value of $d in the expression in which $d resides, then decrement $d by 1.

Increment and decr ement operators.

Increment and Decrement Operators

Page 32: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

1 #!/usr/bin/perl

2 # Fig. 2.14: fig02_14.pl

3 # Demonstrates the difference between pre- and postincrement

4

5 $c = 5;

6 $d = 5;

7

8 print $c, " "; # print 5

9 print $c++, " "; # print 5 then postincrement

10 print $c, "\n"; # print 6

11

12 print $d, " "; # print 5

13 print ++$d, " "; # preincrement then print 6

14 print $d, "\n"; # print 6

5 5 65 6 6

Print variable $c.Use the postincrement operator to use the current value of $c in the expression and then increment $c by 1.

Print the new value of variable $c.

Use the preincrement operator to increment $c by 1 and then use the new value of $c in the expression.

Page 33: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Operator(s) Associativity Called

( ) left to right parentheses

++ or -- none increment and decrement

** right to left exponentiation

*, / or % left to right multiplicative

+ or - left to right additive

=, +=, -=, *=, /=, %= or **=

right to left assignment

Precedence and associativity of operators discussed so far.

Precedence and Associativity of Operators

Page 34: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Run-time logic errors

Such an error can be tricky to find, unless you run your programs using perl with the –w command line option, as in

perl –w filename

This command requests that perl report additional warning messages. In the case of the accidental use of = = (instead of = ), perl will likely catch the error and return a message like

useless use of numeric eq (= =) in void context

with the line number of the expression that contains the problem.

On UNIX and Linux systems #! /usr/bin/perl -w

Forces the program always to execute with warnings enabled

Page 35: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

String Operators•Perl has a collection of arithmetic, equality and relational operators for use with numeric scalars

For example: eq, lt, gt, le, ge are relational operators and compares ASCII value of each character if ( “rabbit” gt “dragon” )A word beginning with A (65) is less than a word beginning with a (97),1 (49) is less than that of 2 (50).•Perl also has special operators for “adding” and “multiplying” strings

The concatenation operator . , and the string repetition operator, x.

>$name = “Serdar”;>$greeting = “Hello, “ . $name . “!”;>Hello, Serdar!

>$lamp = “wish” x 3;>$lamp = “wishwishwish”;

Page 36: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

CONTROL STRUCTURESAlgorithms

• Any computing problem can be solved by executing a series of actions in a specific order. A procedure for solving a problem in terms of

1. the actions to be executed and,2. the order in which the actions are to be executedis called an algorithm.

Consider the “rise-and-shine algorithm” followed by the one junior executive for getting out of bed and going to work:

(1) Get out of bed, (2) take off pajamas, (3) take a shower, (4) get dressed, (5) eat breakfast, (6) car pool to work.

Suppose that the same steps are performed in a slightly different order.Specifiying the order in which statements are to be executed in a computer

program is called program control.

Page 37: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Control Structures- if -

if ( statement satify) {... }elsif ( statement satisfy) {...} else {...}

Page 38: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Standard algebraic equality operator or relational operator

Perl equality or relational operator

Example of Perl condition

Meaning of Perl condition

Relational operators

> > $x > $y $x is greater than $y

< < $x < $y $x is less than $y > >= $x >= $y $x is greater than

or equal to $y < <= $x <= $y $x is less than or

equal to $y Equality operators

= == $x == $y $x is equal to $y

= != $x != $y $x is not equal to $y

Equality and relational operators.

Equalitiy and Relational Operators

Page 39: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

1 #!/usr/bin/perl

2 # Fig. 2.17: fig02_17.pl

3 # Using if statements with relational and equality operators

4

5 print "Please enter first integer: ";

6 $number1 = <STDIN>;

7 chomp $number1;

8

9 print "Please enter second integer: ";

10 $number2 = <STDIN>;

11 chomp $number2;

12

13 print "The integers satisfy these relationships:\n";

14

15 if ( $number1 == $number2 ) {

16 print "$number1 is equal to $number2.\n";

17 }

18

19 if ( $number1 != $number2 ) {

20 print "$number1 is not equal to $number2.\n";

21 }

22

23 if ( $number1 < $number2 ) {

24 print "$number1 is less than $number2.\n";

25 }

26

27 if ( $number1 > $number2 ) {

28 print "$number1 is greater than $number2.\n";

29 }

30

Prompt the user for two numbers, read in the numbers, and remove the newline characters with chomp.

The if structure compares the values of variable $number1 and variable $number2 to test for equality.

The body of the if structure, enclosed by a pair of braces ({}), executes if the condition evaluates to true.

The equality operator != tests whether $number1 and $number2 are not equal.

The relational operator < tests whether $number1 is less than $number2.

The relational operator > tests whether $number1 is greater than $number2.

Page 40: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

31 if ( $number1 <= $number2 ) {

32 print "$number1 is less than or equal to $number2.\n";

33 }

34

35 if ( $number1 >= $number2 ) {

36 print "$number1 is greater than or equal to $number2.\n";

37 }

Please enter first integer: 3Please enter second integer: 7The integers satisfy these relationships:3 is not equal to 7.3 is less than 7.3 is less than or equal to 7.

Please enter first integer: 22Please enter second integer: 12The integers satisfy these relationships:22 is not equal to 12.22 is greater than 12.22 is greater than or equal to 12.

Please enter first integer: 7Please enter second integer: 7The integers satisfy these relationships:7 is equal to 7.7 is less than or equal to 7.7 is greater than or equal to 7.

The relational operator <= tests whether $number1 is less than or equal to $number2.

The relational operator >= tests whether $number1 is greater than or equal to $number2.

Page 41: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Operators Associativity Type

() left to right parentheses

++ -- none increment and decrement

** right to left exponential * / % left to right multiplicative + - left to right additive < <= > >= none relational == != none equality = += - = *= /= %= **= right to left assignment Precedence and associativity of operators discussed so far.

Precedence and Associativity of operators

Page 42: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

1 #!/usr/bin/perl

2 # Fig. 2.19: fig02_19.pl

3 # Program to illustrate numeric and string context, and undef

4

5 $string = "Top 10";

6 $number = 10.0;

7 print "Number is 10.0 and string is 'Top 10'\n\n";

8

9 $add = $number + $string; # 10 (not 20)

10 print "Adding a number and a string: $add\n";

11

12 $concatenate = $number . $string; # '10Top 10'

13 # (not '10.0Top 10')

14 print "Concatenating a number and a string: $concatenate\n";

15

16 $add2 = $concatenate + $add; # 20 (not 30, not 1020)

17 print "Adding the previous two results: $add2\n\n";

18

19 $undefAdd = 10 + $undefNumber;

20 print "Adding 10 to an undefined variable: $undefAdd\n";

21

22 print "Printing an undefined variable: $undefVariable(end)\n";

Number is 10.0 and string is 'Top 10' Adding a number and a string: 10Concatenating a number and a string: 10Top 10Adding the previous two results: 20 Adding 10 to an undefined variable: 10Printing an undefined variable: (end)

The binary addition operator evaluates strings in numeric context. If nothing can be interpreted as numeric, the string evaluates to 0.

The concatenation operator evaluates $number in string context, in this case “10”.

When using a string in numeric context, Perl stops conversion at the first character that cannot be used in numeric context.

When an undefined variable is found in numeric context, it evaluates to 0.

When an undefined value is interpreted in string context, it evaluates to an empty string (“”).

Page 43: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

$total = $total + $grade;add grade to total

$counter = $counter + 1;add 1 to counter

Flowcharting Perl’s sequence structure

Page 44: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Control Structureswhile

do {

...

}while ( statement)

while ( statement) {

...

}

Page 45: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Control Structuresuntil

do {

...

}until ( statement)

until ( statement) {

...

}

Page 46: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

sales >= 50true

false

print “Earned bonus!”

sales >= 50false

true

print “You did not earn your bonus.”

if selection structure

unless selection structure

$total = $total + grade;

$counter = $counter + 1;

Flowcharting the single-selection if (top) and unless (bottom)Control Structures

Page 47: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

truefalse$sales >= 50

print “Earned bonus!”print “You did not earn your bonus.”

 

Flowcharting the double-selection if/else control structure

print “You did not earn your bonus.” print “Earned bonus!”

Page 48: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

true

$product = 2 * $product$product <= 1000

false

Flowcharting the while repetition structure

$product <= 1000

$product = 2 * $product

Page 49: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

1 #!/usr/bin/perl

2 # Fig. 3.5: fig03_05.pl

3 # Using the do/while repetition structure

4

5 $counter = 1;

6

7 do {

8 print "$counter ";

9 } while ( ++$counter <= 10 );

10

11 print "\n";

1 2 3 4 5 6 7 8 9 10

The do/while repetition structure repeatedly prints the value of variable $counter while the variable is less than or equal to 10.

After the each execution of the body of the loop, the control variable $counter is pre-incremented.

Page 50: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

1 #!/usr/bin/perl

2 # Fig. 3.6: fig03_06.pl

3 # Using the do/until repetition structure

4

5 $counter = 10;

6

7 do {

8 print "$counter ";

9 } until ( --$counter == 0 );

10

11 print "\n";

10 9 8 7 6 5 4 3 2 1

The do/until repetition structure repeatedly prints the value of variable $counter until the variable is equal to 0.

After the each execution of the body of the loop, the control variable $counter is pre-decremented.

Page 51: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Flowcharting the do/while repetition structure

false

true

--$counter == 0

print "$counter ";print “$counter “;

++counter <= 10

Page 52: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

false

true

--$counter == 0

print "$counter ";print “$counter “;

--counter == 0

Flowcharting the do/until repetition structure

Page 53: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

1 #!/usr/bin/perl

2 # Fig. 3.10: fig03_10.pl

3 # Average-sales problem with counter-controlled repetition

4

5 # initialization phase

6 $total = 0; # clear total

7 $weekCounter = 1; # prepare to loop

8

9 # processing phase

10 while ( $weekCounter <= 10 ) { # loop 10 times

11

12 # prompt for input and input a sales value

13 print "Enter sales for week $weekCounter: ";

14 chomp( $sales = <STDIN> );

15

16 $total += $sales; # add sales to total

17 ++$weekCounter; # increment counter

18 }

19

20 $average = $total / 10; # divide to find average

21 print "\nSales averaged $average computers per week\n";

The while structure executes while $weekCounter is less than or equal to 10.

Displays a prompt to the user for the next sales amount.

The value the user inputs is stored in variable $sales. Function chomp immediately removes the newline character from the input value.

The program updates $total with the new $sales value entered by the user.

Adds 1 to variable $weekCounter so the condition in the while structure will eventually become false.

Assigns the result of the averaging calculation to variable average.

Page 54: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Enter sales for week 1: 56Enter sales for week 2: 52Enter sales for week 3: 64Enter sales for week 4: 72Enter sales for week 5: 56Enter sales for week 6: 58Enter sales for week 7: 62Enter sales for week 8: 63Enter sales for week 9: 48Enter sales for week 10: 52 Sales averaged 58.3 computers per week

Page 55: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

1 #!/usr/bin/perl2 # Fig. 3.12: fig03_12.pl3 # Average-sales problem with sentinel-controlled repetition4 5 $total = 0;6 $weekCounter = 0;78 print "Enter sales for week or enter quit: "; 9 chomp( $sales = <STDIN> );1011 until ( $sales eq 'quit' ) { 12 $weekCounter++;13 $total += $sales;14 print "Enter sales for week or enter quit: "; 15 chomp( $sales = <STDIN> );16 }1718 if ( $weekCounter != 0 ) {19 $average = $total / $weekCounter;20 print "\nSales averaged $average computers per week.\n";21 }22 else {23 print "\nNo sales figures were entered.\n";24 }

Receive input from user before entering until structure.

The until structure executes until the user enters the sentinel value.

The program updates $total with the new $sales value entered by the user.

The next value is entered by the user before the end of the until structure’s body.

The if/else structure determines whether any values have been entered by the user.

If values have been entered, the program calculates and outputs the average of all values.

If variable $weekCounter is 0, a string is output indicating that no values have been entered.

Page 56: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Enter sales for week or enter quit: 57Enter sales for week or enter quit: 86Enter sales for week or enter quit: 52Enter sales for week or enter quit: 48Enter sales for week or enter quit: quit Sales averaged 60.75 computers per week

Page 57: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

1 #!/usr/bin/perl

2 # Fig. 3.14: fig03_14.pl

3 # Analysis of sales results

4

5 # initialize loop variables

6 $metQuota = 0; # employees who met quota

7 $didNotMeetQuota = 0; # employees who did not meet quota

8 $employeeCounter = 1; # employee counter

9

10 # process 10 employees; counter-controlled loop

11 while ( $employeeCounter <= 10 ) {

12 print "Enter quota result, (yes or no): ";

13 chomp( $result = <STDIN> );

14

15 # conditional operator nested in while

16 $result eq 'yes' ? ++$metQuota : ++$didNotMeetQuota;

17

18 $employeeCounter++;

19 }

20

21 # termination phase

22 print "\nMet quota: $metQuota\n";

23 print "Failed to meet quota: $didNotMeetQuota\n";

24

25 if ( $metQuota > 8 ) {

26 print "Raise holiday bonuses!\n";

27 }

The while structure executes while variable $employeeCounter is less than or equal to 10.

The conditional operator increments variable $metQuota if the user has entered yes. Variable $didNotMeetQuota is incremented if the user has entered no.

If variable $metQuota’s value is greater than 8, a string is output to the user indicating that holiday bonuses should be raised.

Page 58: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Enter quota result, (yes or no): yesEnter quota result, (yes or no): yesEnter quota result, (yes or no): noEnter quota result, (yes or no): yesEnter quota result, (yes or no): yesEnter quota result, (yes or no): yesEnter quota result, (yes or no): yesEnter quota result, (yes or no): yesEnter quota result, (yes or no): yesEnter quota result, (yes or no): yes Met quota: 9Failed to meet quota: 1Raise holiday bonuses!

Enter quota result, (yes or no): noEnter quota result, (yes or no): noEnter quota result, (yes or no): noEnter quota result, (yes or no): noEnter quota result, (yes or no): yesEnter quota result, (yes or no): yesEnter quota result, (yes or no): noEnter quota result, (yes or no): noEnter quota result, (yes or no): yesEnter quota result, (yes or no): no Met quota: 3Failed to meet quota: 7

Page 59: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

EXAMPLE#!/usr/bin/perl -w# cookie.pl script# Cookie Monster

$cookie = “”;

while ( $cookie ne ‘cookie’) {print ‘Give me a cookie: ‘;chomp ($cookie = <STDIN>);}

print “Nihayet Cookie.\n”;

% cookie.plGive me a cookie: asdfGive me a cookie: exitGive me a cookie: quitGive me a cookie: stopGive me a cookie: £$”^&!)(@Give me a cookie: cookieNihayet Cookie.

Page 60: System Programming in Operating Systems ITU Informatics Institute Dr. Serdar Çelebi.

Need extra Help!

% man perlfunc (or perlop)

% perldoc perlfunc

% perldoc –f chomp

http://www.perldoc.com/


Recommended