Main Content

Perl from basics

Archive - Originally posted on "The Horse's Mouth" - 2011-06-20 19:46:41 - Graham Ellis

It's refreshing to teach Perl to a class of bright but brand new programmers, which I'm doing in Edinburgh this week. For a class on novices really make me think "why" at some of the aspects us old hacks take for granted. And - yes - I'm delighted to step back to the basics and explain.

Along these lines ... here's a Perl program from today with, incredibly even for me, every line commented - in fact, I wrote the comments first - like an ASCII flowchart if you like, then added the code to perform each action thereafter.


# set up the tax rate
$factor = 1.2;
 
# Ask for the amount net
print "How much does the storekeeper want for this widgit? ";
 
# read and store the answer
$net = <STDIN>;
 
# calculate the gross amount
$gross = $factor * $net;
 
# and print it out
print "The amount to charge is ",$gross,"\n";


"Did you have to put the 1.2 into a separate variable - couldn't you just have multiplied by it?" (Discussion of the dangers of riffling your code with constants)

"Is the spacing important" (Discussion of the spaces to make the layout look good, and also of those extra spaces in the strings being printed out)

And looking at variable naming, printed result accuracy, whether the report generated should echo the input data, and more ... amazing how much you can learn from 4 lines of executable code!