Main Content

Perl - Subs, Chop v Chomp, => v ,

Archive - Originally posted on "The Horse's Mouth" - 2008-10-08 08:10:53 - Graham Ellis

During courses, I end up writing a lot of short demonstrations to show particular features of a language - this week, it's a Perl Programming Course so those examples are in Perl.

Some interesting Perl facts ...

a) The => operator can be used to replace the , ("the equals, greater than can be used to replace the comma")

b) chop and chomp have the same effect on a line of text just read in from STDIN (which usually means "read from the keyboard")

c) It's a good idea to take commonly repeated pieces of code and save them in a block - called a sub or subroutine in Perl - so that you don't have to keep repeating yourself AND so that you can present your user with a consistent interface

The programs I come up with are odd / quirky / memorable and if you look back at them later will leave the new reader scratching his or her head - but the key word is memorable. Here's the program that went some of the way to explaining the key perl facts above:

sub getui {
  print "$_[0] - ";
  chomp ($rv = <STDIN>);
  return $rv;
  }
 
print "How kids yagot? ";
chomp($nk = <STDIN>);
 
print "And how many goldfish? ";
chop($ng = <STDIN>);
 
$nz = getui("how many zebras?");
 
print "Actimel $nk pounds\n";
print "Cream Cheese ",$nk," kiddoes\n";
print "Milk $nk pounds\n";
print "Yoghurt "=>$ng=>" goldfish\n";
print "Bananas ",$nz," zebras\n";


Learning in this way is not only useful, but fun! If you're looking for the dates of the next public Perl course ... as I write (early October 2008) the next course starts on 27th October, and if you're reading this later on the archive and have missed that start date, you can find what's coming up here in our index of courses. I look forward to helping many more people (such as yourself, perhaps?) enjoy learning Perl!




Sample Output:

Dorothy:p1 grahamellis$ perl tootoo
How kids yagot? 3
And how many goldfish? 7
how many zebras? - 4
Actimel 3 pounds
Cream Cheese 3 kiddoes
Milk 3 pounds
Yoghurt 7 goldfish
Bananas 4 zebras