5.10 Exercises

5.10 Exercises

1.  (Easy: Documentation Reading)

Use perldoc to learn about modules and object-oriented programming in Perl. Read the sections given in Table 5.7 by providing the section name as an argument to perldoc.

 


Section Name

Description

 

perlmod

How Perl modules work

 

 

perlmodlib

How to write and use Perl modules

 

perlmodinstall

How to install Perl modules from CPAN

 

perlobj

Perl objects

 

perlboot

Perl object-oriented tutorial for beginners

   

 

Table 5.7:  Modules and Object-oriented Programming in Perl

If you downloaded Perl from www.cpan.org, these should be automatically installed in your system. If you cannot find these on your system, visit www.cpan.org and read the documentation on these topics.

2.  (Easy: Documentation Reading)

There is a very large number of Perl modules contributed by individuals from around the world. Visit www.cpan.org on the Web and get an overall view of the modules available at the current time. They are classified according to the type of work they perform. Read detailed documentation on modules that interest you.

3.  (Easy: Module Installation)

Install two modules of your choice from www.cpan.org. Perform installation on your own, without using an installation tool. That is, go through the steps discussed in this Chapter. Document any problems, if any, you face during installation. Try to find solutions for your problems. Write simple application scripts to test that the modules you install work. Figure out where files corresponding to modules are helpt on your system. Read documentation on these modules on your system using perldoc.

4.  (Easy: Class Definition)

Define a class called Circle in a file of its own. It has three fields: centerX, centerY and radius. These are exported for others to access. Define two methods: findCircumference and findArea in the Circle class. The class has a constructor that takes no arguments and sets all the class fields or
variables to undefined values.

Now, in a separate file circles.pl, define an instance of Circle called myCircle. Specify values to myCircle’s fields: centerX, centerY and radius. Compute the area and circumference of myCircle and print them.

5.  (Easy: Class Definition, Several Constructors)

Define a class called Circle in a file of its own. The class has three fields or properties: centerX, centerY and radius. It also has three constructor methods: new, new1 and new2. new does not take any arguments and sets the values of the three fields to undefined values. new1 takes three arguments correspoding to centerX, centerY and radius. It sets the values of the fields to the values passed from the call. new2 takes a value corresponding to radius as argument. It sets the value of the field to the
argument passed to it.

It also has two non-constructor methods: findCircumference and findArea as in the previous problem.

Write an application file circles.pl. Make calls to each one of the three constructor methods and the two non-constructor methods. Create three instances of circles. Provide values for the three fields of each circle. Use the toString method to print each circle’s details in a readable manner.

6.  (Easy: Printing Values in Readable Format)

Extend the code you write for the previous problem by adding a toString method in the Circle class. It prints the values of the fields of an instance of Circle in a nice readable string format.

7.  (Easy: Class Definition, Several Constructors)

Define a class called Person. It has four fields: name, age, homeTown and profession. There are three constructor methods: make, make1, and make2. make takes four arguments corresponding to the four fields. make1 takes two arguments corresponding to name and profession. make2 takes an argument corresponding to name.

Write an application script person.pl and make the following calls.

 

$jugal = Person->make1 ("Jugal", "professor");

$justin = Person->make ("Justin", 19, "model", "Colorado Springs");

$christopher = Person->make2 ("Christopher", "software engineer");

 

8.  (Easy: Class Definition)

Define a class Name in a file of its own. It has three fields: firstName, lastName and title. These are exported. It has one constructor function: new that takes two arguments, corresponding to firstName and lastName. It sets the values appropriately. The method setTitle gets one argument and uses it to set the value of the title field. getInitails returns the value of the firstName field. The method getLastFirst returns a string containing the last name, followed by a comma, followed by the first name. The method getFirstLast returns a string containing the first name followed by the last name.

Write a script names.pl that assigns values to the variables and then calls the methods.

9.  (Easy: Class Definition, Inheritance)

Write two class definitions: Rectangle and Square. A Rectangle has several exported fields: height, width, perimeter and area. The class has a constructor new that takes two number corresponding to height and width as argument. It has three other methods; findPerimeter, findArea
and toString. The method findPerimeter computes the perimeter of a rectangle. The method findArea computes the area of a rectangle. toString returns a string containing the values of a rectangle’s four fields in an easily readable format. The string returned can be printed to gather information about instances of rectangles.

The class Square is a subclass of Rectangle. It has one method toString. It inherits from Rectangle. It has no other methods of its own. This toString method overrides the toString method of the parent class.

Write a script geometry.pl that instantiates a rectangle and a circle and prints their areas, perimeters and string descriptions.

10.  (Easy: Class Definition, Random Numbers)

Define a class called Dice in a file of its own. It has six instance fields, one field for each face. For example, we may have an instance of a dice whose faces are labeled 1,2,3,3,4 and 4 respectively. Write an instance method throwDice() that simulates a throw of a dice. When one throws a dice, one of the faces shows up on top at random. The method returns the integer etched on the face on top.

Write a script called dice.pl that creates an instance of a Dice, and assigns labels to each of the faces of the dice. Make a few calls to throwDice to simulate a sequence of dice throws.

11.  (Easy: Class Definition, Time String Formats)

Define a class called Time with the following instance fields: year, month, date, and hour. Each one of these fields is an integer. The field hour stores the hour in a military style ranging from 0 to 23, 0 being midnight and 12 being noon. The year field is stored as an integer that has four digits in it,
such as 2002. Make sure the constructor and other methods check for validity of the data provided as argument.

Write a method toString() for this class that returns the time. Sample calls to toString() return the following.

 

4 PM on 4/5/02

6 AM on 4/5/02

noon on 4/5/02

midnight on 4/5/02

 

For the cases given above, the values of the fields (i.e., year, month, date and hour) for the instances of the Time class are

 

2002, 4, 5, 16

2002, 4, 5, 6

2002, 4, 5, 12

2002, 4, 5, 0

 

respectively.

12.  (Easy: Class Definition, Arithmetic, Geometry)

Define a class called Rectangle. It has four fields: bottmLeftX, bottomLeftY, height and width. The first two fields give the X and Y coordinates of the bottom left vertex in two-dimensional space. All fields are exported.

(a) Write a method called findPerimeter() for the class that takes no argument and returns the area of a rectangle.

(b) Write a second method by the name findCircleRadius() that returns the radius of the circle that has the same perimeter as that of a rectangle.

(c) Write a third method called printTopRight() that takes no argument and returns nothing, but prints to screen the X and Y coordinates of the top right vertex of a rectangle.

Assume that values of X increase toward the right of the screen. Also assume that values of Y increase toward the top of the screen.

Write a script called rectangles.pl and make sample calls to all methods.

13.  (Easy: Class Definition, Arithmetic, Geometry)

Define a class called Sphere. A sphere is an object that has three-dimensional extent. A sphere has a center and a radius. It takes three coordinates to specify the center of an instance of Sphere. Declare the data fields for the Sphere class accordingly. In addition, allow each instance of a sphere to have fields for storing its surface area and volume.

Now, we define four constructors for the Sphere class. Let the first constructor take three coordinates and a radius and create an instance of Sphere. The second constructor creates an instance of Sphere given a radius. It makes the center default to (0.0, 0.0, 0.0), the origin of the three dimensional space. The third constructor creates an instance of a sphere with the same radius and center as that of another. The fourth constructor creates an instance of
Sphere and makes the center default to (0.0, 0.0, 0.0) and the radius default to 1.0.

Define a method findArea to compute the surface area of a sphere. Define a method findVolume to compute the volume of a sphere. Define a method called toString() that takes no argument and returns a string containing the details of an instance of Sphere. You will call this method several times to print the details of the spheres in an accompanying script called spheres.pl.

In spheres.pl create four instances of Sphere. The first one has its center at (2.0, 3.0, 4.0) and radius 1.0. The second one simply has a radius of 5.0 as is located at the default location of (0.0, 0.0, 0.0). The third one is located where the first one is located. Its radius is same as that of the first one. The fourth one has a default radius of
1.0 and the center is located at (0.0, 0.0, 0.0, 0.0).

Make sure you call each of the constructors you define at least once.

Compute the surface areas and the volumes of the four spheres. Store the surface areas and volumes for the spheres in the fields that you have defined for them when you defined the class Sphere. Print the results in a nicely formatted table. Use the toString method to print the details of a sphere instance.

14.  (Medium to Hard: Class Definition, Family Relatoinships, Inheritance)

In this problem, you enter information about individuals in the Kalita family and print information out about individuals in the family as asked. The information you see is fictitious.

You define two classes that work together to solve this problem. The classes are Person and Date. You define each class in a separate file. Also, write a script called kalitas.pl.

Next, define a class called Date in a file called Date.pm. An instance of Date has three data fields: year, month, and date. Each one of this is an integer. The class has one constructor. It takes a year, a month, and a date as input.

There is a second method in the class called before() that takes an argument that is another instance of the class Date. It returns a boolean. In particular, if we have declared $d1 and $d2 as given below:

 

  $d1 = Date->new (2002, 1, 12);

  $d2 = Date->new (2002, 2, 28);

 

the call

 

  $d1->before ($d2);

 

returns true.

There is a third method in the class called toString(). It returns a string corresponding to an instance of the Date class. For example, corresponding to $d1 above, it returns the string "1/12/2002".

You now define a class called Person in a separate file called Person.pm. The fields are firstName, middleName, yearlyIncome, birthDay, mother and father. Note that birthDay is of type Date. mother and father are of type
Person. firstName and middleName are string. The class has several methods. You can write more methods than asked if you think it helps solve sub-problems for the methods that I ask. There is a constructor that takes a first name (a string) and a date of birth (a Date).

There are two methods setFather() and setMother(). Each one takes a Person as argument. They give values to the father and mother fields respectively.

Now, define a method called findFather() that finds the father of a certain person. It returns an object of type Person. Note that we may not have a father for each person. In such a case, return an undefined value.

Define a method called findFatherName() that returns the first name of the father of a certain person. If there is no father, it returns the string "Unknown". This method should call the findFather() method defined above.

Now, define a method called findMother() that finds the mother of a certain person. It returns an object of type Person. Note that we may not have a mother for each person. In such a case, return an undefined value.

Define a method called findMotherName() that returns the first name of the mother of a certain person. If there is no mother, it returns the string "Unknown".

Now, define a method called findPaternalGrandFather() that finds the paternal grand father of a certain person. It returns an object of type Person. Note that we may not have a paternal grandfather for each person. In such a case, return an undefined value.

Define a method called findPaternalGrandFatherName() that returns the first name of the paternal grand father of a certain person. If there is no paternal grandfather, it returns the string "Unknown".

Next, write a method setYearlyIncome() to set the yearly income of a certain person. Write a method findRicher() that finds the richer of two persons. The next method is called

findOlderPersonName(). It finds the name of the older between two persons. Finally, write a toString() method to print details about an individual. It can help you print the family relationship table you need to print in the application file kalitas.pl.

The file kalitas.pl creates instances of individuals in the Kalita family performs computations using the methods defined for the two classes specified earlier. Create seven instances of Person with the following details.

 


First Name

Date of Birth

 

Joel

July 5, 1966

 

 

Jake

July 5, 1966

 

Mukul

December 14, 1960

 

Dole

September 11, 1967

 

Ben

March 10, 1933

 

Nirala

August 15, 1943

Ron

January 21, 1998

 

   

 

Use the setFather() method in the Person class to indicate the following.

 


First Name

Father

 

Joel

Ben

 

 

Jake

Ben

 

Mukul

Ben

 

Dole

Ben

Ron

Jake

 

   

 

Use the setMother() method in the Person class to indicate the following.

 


First Name

Mother

 

Joel

Nirala

 

 

Jake

Nirala

 

Mukul

Nirala

Dole

Nirala

 

   

 

Next print a table giving the family relationships in the Kalita family. That is, print everyone’s mother and father in a table.

Next, using the setYearlyIncome() method in the Person class, indicate the following.

 


First Name

Yearly Income

 

Joel

59565.05

 

 

Jake

110020.29

 

Mukul

20005.12

 

Dole

5010.31

 

Ben

1100.42

 

Nirala

0

Ron

0

 

   

 

Next, print who is richer of Joel and Jake using the findRicher() method in the Person class. Also, print who is richer of Jake and Dole.

Now, print who is older of Mukul and Joel. Finally, print who is older of Joel and Jake. Use the

findOlderPersonName() method in the Person class to do so.

15.  (Medium to Hard: Class Definition, Arithmetic, Amortization)

There are three overall goals to the assignment. First, you will print a loan amortization table assuming the loan uses simple interest. Second, you will print a table that shows how many months it takes to pay back loans. You will do this varying the principal borrowed, the rate of interest and the monthly payment.

What classes do you need to define

This assignment asks you to define a class called Loan to solve a problem. You also write an application script called loans.pl. You can write any other classes and methods if you think it will help solve the problem.

Class Loan

Define a class called Loan in a file called Loan.pm. An instance of Loan has four data fields: principal, rate, and principalRemaining and monthlyPayment.

You need to write two methods for this class. You can write additional methods if it helps you.

There is a method in the class called printPaymentTable() that takes no argument. It prints an amortization table given a Loan object with a certain principal, a certain rate of interest and a certain monthly payment.

This is how we calculate the amortization or payment table. Suppose you take out a loan with principal p, rate of interest r, and monthly payment m. We assume that interest is calculated monthly and it is simple interest.

We assume that during the month we take out the loan, we do not pay anything. But, starting the next month, which we call the first month of the loan, we pay a fixed amount back to the lender. This amount is m. This amount is divided by the lender into two parts. The first part i goes to pay interest on the principal remaining at the beginning of the month. and the next part l goes to lower the principal. i is computed using the standard formula for simple interest which is

 

                                                                     i=p*n*r/100

 

where n is the duration in years for which the interest is computed. Here, we are talking about a month and hence .

l is computed as m-i. So, every month the principal is reduced by an amount equal to l. Therefore, the next month when we calculate interest, it is calculated on the remaining principal, not the principal we borrowed to start with.

Every month subsequent to the first month, we pay to the lender the same monthly payment m, but progressively the share of it toward interest comes down because the principal keeps on getting smaller. Consequently, in every subsequent month, we pay more toward the principal.

As a result of our payments, the principal keeps on coming down, and finally one month, it becomes lower than the monthly payment. This is the last month of the loan’s duration. During this month, we pay the principal remaining and get done with the loan.

The first required method printPaymentTable() for the Loan class computes what is called an amortization table that shows how for every month during the duration of the loan, how much of your monthly payment goes toward the principal, how much goes toward paying interest, and how much principal remains to be paid.

The second method called monthsNeedeToPayBack() is a modification of the first method. This second method tells us how many months are needed to pay back a loan with a certain principal at a certain rate of interest when we have a certain constant monthly payment to make.

Application script loans.pl

It creates instances of loans, changes various fields of loans and prints two tables: an amortization table for a specific loan, and a table showing the number of months to pay back a loan for various values of principal, rate of interest and monthly payment.

First, you print the amortization table for a loan for which the principal is $10,000.00, the rate of interest is 18.00% and the monthly payment is $200.00. We call this instance of a loan: visaLoan.

Next, we print the table that shows the number of months needed to pay back a loan. We vary the amount of principal borrowed from $15,000 to $18,000 increasing with a step of $1000.00. For each loan amount, we vary the rate of interest from 8.00% to 18.00% with a step of 1.00%. For each combination of a principal and a rate of interest, we vary the monthly payment from $100.00 to $1000.00 incrementing with a step size of $100.00. For each combination of principal, rate of interest and monthly payment, we print the number of months needed to pay back the loan.

Just be aware that if the monthly payment is too low, a loan may never be repaid. In such a case, say that the number of months to pay back is infinity. Also, make sure that all your results are printed only up to two decimal places. Perform all your computations to only two places after the decimal. You can perform regular computation with more digits, but you must modify the results in every stage so that they are rounded to two places after the decimal point.