KISS - one action per statement please - Perl
Archive - Originally posted on "The Horse's Mouth" - 2006-12-05 05:25:40 - Graham Ellis"Nice program, Bill - but the output is a bit verbose. Can you take out some print statements". So said one of my delegates' bosses this week, late in the day just before a new application went live. Alas ... the application fell over just because the print had been removed.
In Perl - that was the language in use - you can assign variables within your print statement, and that's what had been done. So taking out the print caused it to fall over. What you can do and what you should do are two different things, and it requires a thoughtful programmer and an excellent manager to the make the best of coding, apply standards and end up with a maintainable program that fits the user's requirement well.
Sample code - what NOT to write:
foreach $value (1..5) {
print ("... ");
print ("Value is now ",$sum+=$value,"\n");
}
print ("Triangle 5 is $sum\n");
Without the print it becomes:
foreach $value (1..5) {
print ("... ");
}
print ("Triangle 5 is $sum\n");
When those are run:
grahamellis$ perl avoidthis
... Value is now 1
... Value is now 3
... Value is now 6
... Value is now 10
... Value is now 15
Triangle 5 is 15
grahamellis$ perl liketheplague
... ... ... ... ... Triangle 5 is
grahamellis$
Does this just apply to print statements? No - anywhere you're undertaking two actions in a single statement is liable to come back an bite you late on.
Don't write
$r = $p++;
as it changes two variables - much clearer to write $r = $p; $p++;
.Don't use printf. PLEASE. As it both formats and prints. Use instead sprintf and then do a separate print. That way, you have the later flexibility to apply further string manipulation - for example if data originally destined for a command window is now to be output to a browser.
You should not write:
printf ("< %.2f",$maxprice);
But rather:
$poundamount = sprintf ("< %.2f",$maxprice);
print $poundamount;
Because you can enhance the latter as follows:
$poundamount = sprintf ("< %.2f",$maxprice);
$poundamount =~ s/</</g;
print $poundamount;
We (or rather "I" - I'll take the blame) made the mistake on a previous version of the Well House Consultants web site too - in HTML. The image on the left is 132 pixels wide, and I wanted an 8 pixel space to the right of it. What easier than to add the 8 white pixels to the images? So that's what I did and built up quite an image library ... to find my self well and truely in trouble when we wanted to add the ability to change background colour for users. We ended up, temporarily, with a dirty looking white band to the right of every image and it was only fixed by a rather messy procedure to - guess what - replace the single image with two functions with two images each with a single function.
Are you familiar with KISS (post title) ... if not, see next post!