Previous Page Next Page

12.5. What's Next?

The next chapter focuses on pointers, also called references. You will learn how to create complex data structures using pointers, how to create anonymous variables, how to dereference pointers, and how to pass them to subroutines.

You will learn the reasons for using pointers in Perl.

Exercise 12: I Hid All My Perls in a Package

1.Write a script called myATM. It will contain two packages: Checking and main. Later, this file will be broken into a user file and a module file.
2.In the myATM script, declare a package called Checking.

It will contain a my variable called balance set to 0.

It will initially contain three subroutines:

  1. get_balance

  2. deposit

  3. withdraw

3.In package main (in the same file), create a here document that will produce the following output:
  1. Deposit

  2. Withdraw

  3. Current Balance

  4. Exit

Ask the user to select one of the menu items. Until he selects number 4, the program will go into a loop to redisplay the menu and wait for the user to select another transaction.

The subroutines will be called in the main package by qualifying the Checking package name with double colons.

If the user chooses number 4, before the program exits, print today's date and the current balance to a file called register.

Can you print the value of the balance without calling the get_balance subroutine from the user script?

4.Rewrite the Checking package so it gets the balance from the file register if the file exists; otherwise, it will start at a zero balance. Each time the program exits, save the current balance and the time and date in the register file.
5.
  1. In Exercise 11 of Chapter 11, you wrote a program called tripper that contained a subroutine called mileage. It asked the user the number of miles he drove and the amount of gas he used. The subroutine was to calculate and return the user's mileage (miles per gallon). The arguments passed to the subroutine are the number of miles driven and the amount of gas used. These values are assigned to my variables. If you haven't written the tripper program, now is a good time to do so.

  2. If the input is a non-number, a negative number, or zero for the amount of gas, use the croak function to print the error message.

    Now create a directory called myfunctions. Change to that directory and create a file called mileage.pl. Put the subroutine mileage in the file mileage.pl.

  3. In your tripper script, update the @INC array and use the require function to include the mileage subroutine. (Be sure that the last line after the closing curly brace of the subroutine is 1.)

6.Move the Checking package from the myATM script into a file called Checking.pm. Now move the Checking.pm module into a directory called "myModules". Update the @INC array in the myATM script that will use the module. Use the Checking module in the myATM script.


Previous Page Next Page