# Perl's Building Blocks: Numbers and Strings

• Print
• + Share This
This chapter is from the book

## Exercise: Interest Calculator

For this exercise, you're going to perform a compound interest calculation. This program will calculate the interest on a savings account, given some information about interest rates, deposits, and time. The formula you're going to use is as shown here:

Using your text editor, type the program from Listing 2.2 and save it as Interest. Do not type in the line numbers. Make the program executable according to the instructions you learned in Hour 1.

When you're done, try running the program by typing the following at a command line:

#### Listing 2.2 The Interest Program

```1:  #!/usr/bin/perl -w
2:
3:  print "Monthly deposit amount? ";
4:  \$pmt=<STDIN>;
5:  chomp \$pmt;
6:
7:  print "Annual Interest rate? (ex. 7% is .07) ";
8:  \$interest=<STDIN>;
9:  chomp \$interest;
10:
11: print "Number of months to deposit? ";
12: \$mons=<STDIN>;
13: chomp \$mons;
14:
15: # Formula requires a monthly interest
16: \$interest/=12;
17:
18: \$total=\$pmt * ( ( ( 1 + \$interest) ** \$mons ) -1 )/ \$interest;
19:
20: print "After \$mons months, at \$interest monthly you\n";
21: print "will have \$total.\n";```
`perl Interest`

Listing 2.3 shows a sample of the Interest program's output.

Line 1: This line contains the path to the interpreter (you can change it so that it's appropriate to your system) and the -w switch. Always have warnings enabled!

Line 3: The user is prompted for an amount.

Line 4: \$pmt is read from the standard input device (the keyboard).

Line 5: The newline character is removed from the end of \$pmt.

Lines 7–9: \$interest is read in from the keyboard, and the newline is removed.

Lines 11–13: \$mons is read in from the keyboard, and the newline is removed.

#### Listing 2.3 Output from the Interest Program

```1: Monthly deposit amount? 180
2: Annual Interest rate? (ex. 6% is .06) .06
3: Number of months to deposit? 120
4: After 120 months, at 0.005 monthly you
5: will have 29498.2824251624.```

Line 16: \$interest is divided by 12 and stored back in \$interest.

Line 18: The interest calculation is performed, and the result is stored in \$total.

Lines 20–21: The results are printed.
• + Share This
• 🔖 Save To Your Account