Create a compound interest calculator in Perl

Business

Open a text editor, such as Notepad, and enter the following lines of code:

#!/usr/bin/perl -w

print “Monthly deposit: “; # input request
$deposit=; # get input from the keyboard
chomp $deposit; # remove the newline character from the end of the variable

print “Interest rate (3, 4, 5.5, etc.): “; # input request
$interest=; # get input from the keyboard
chomp $interest; # remove the newline character from the end of the variable

# Change the interest of 3, 4, 5, etc. to .03, .04, .05, etc.
$interest=$interest*.01;

# Change the interest to a monthly multiplier
$interest=$interest/12;

print “Number of months: “; # input request
$nMonths=; # get input from the keyboard
chomp $nMonths; # remove the newline character from the end of the variable

# The interest calculation
$total=$deposit * (((1 + $interest) ** $nMonths) -1 ) / $interest;

print “After $nMonths months you will have a total amount of $total”;

(Note: The spaces on either side of STDIN are for display purposes only in this article. You can omit them in your script.)

Save the script as interest.pl. Take note of the directory/folder where you have saved it.

Running the script

You must run the script from a command line prompt, so open an MS-DOS prompt/terminal window. Change to the directory/folder where the interest.pl the file is found and type the following command:

interest perl.pl

When prompted, enter the monthly deposit, the interest rate, and the number of months the money is deposited.

message error

If the script didn’t work, you probably received one of the following error messages:

  • ‘Bad command or file name’ or ‘command not found’. This means that Perl has not been added to the PATH variable. Consult the help/documentation of your operating system for information on how to solve this problem.
  • ‘Cannot open interest.pl perl script: a file or directory does not exist’. This probably means it’s not in the folder/directory where you saved the script, in which case you need to change to the correct location.
  • If you get a syntax error, it probably means that you have mistyped the contents of the file. Open the file and correct any errors.

Leave a Reply

Your email address will not be published. Required fields are marked *