Perl: subroutines

The tutor continues about programming with Perl.  Tutoring computer science, subroutines have both theoretical and practical importance.

 
Back in my November 14 post I opened up the discussion on subroutines. In computer science, a subroutine is a self-contained body of code that performs a specific task.

Today, we’ll look at a simple example: a subroutine that calculates the final price of merchandise with a price, discount, and tax rate given by the user. The subroutine itself resides at the bottom of the program, but is called earlier.

#!/usr/bin/perl
print “Hello. Welcome to the final price calculator.\n”;
print “Enter the sticker price of the merchandise, please.”;
$price=<STDIN>;
print “Enter the discount percentage, if there is one.\n”;
print “For example, 25 means 25 percent off.”;
$discount=<STDIN>;
if(!$discount){
$discount=0;
}
print “Now, enter the tax percentage; eg., 12 means 12 percent.”;
$taxrate=<STDIN>;
&finalprice($price,$discount,$taxrate);

sub finalprice{
$finprice=$_[0]*(1-$_[1]/100)*(1+$_[2]/100);
print “Sticker price is $_[0]”;
print “Discount is $_[1]”;
print “Tax rate is $_[2]\n”;
print “The final price at the till should be $finprice\n\n”;
}

Note the subroutine definition starts with sub. A subroutine defined as sub bob1 would be invoked with the call &bob1(parameter list).

For Christmas Day, this is probably enough. I will be discussing the issue of parameters in a coming post.

To all my readers: Happy Holidays. As with every post, I hope this one finds you in good spirits:)

Source:

McGrath, Mark. Perl in easy steps. Southam: Computer Step, 2004.

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Leave a Reply