Main Content

Learning to use existing classes in Perl

Archive - Originally posted on "The Horse's Mouth" - 2012-08-10 08:16:39 - Graham Ellis

If you've got a whole lot of logic that you want to be able to run on data of a certain type, you'll typically put all of that logic into a grouping of its own - typically known as a package or a class, and you'll then call that logic at a high level from outside the package or class. This is a great approach for writing code that is reusable, each to test and easy to maintain. And it means that others (who don't have any in depth understanding of the internals of handling the data type) can easily use your logic.

For the updated Perl Programming course that I am trialing this week, I have written a new class (and put it [here]), and I'm showing delegates how to make use of the class before I teach them a little bit about how to write such classes of their own.

Here's how to make use of that class ... firstly, load in the logic from its own file:

  use train;

And then you can call / make use of that logic using explicit predefined subs known as methods:

  $soton = new train(3,74);
  $l1 = $soton->getlength();
  $c1 = $soton->getcapacity();
  $s1 = $soton->getcapacity(1.0);
  print "Southampton: $l1 $c1 $s1\n";


The result of running that is

  Southampton: 69 310 222

which tells us that the train is 69 metres long, has 222 seats, and a capacity of 310 passengers. You may wonder about how these figures are reached - the good news is that as a user of the class you don't need to know the algorithms that are used - you can just call the code.

Full test program is [here] - we've created several train objects in that program to give a little more help in training, and from a testing viewpoint we need to check that the code works with several trains of different lengths and seating arrangements - in other words that variables are different for each train and not shared. We've also provided a second test program [here] to start showing class reuse

You'll learn how to use objects on our Learning to program in Perl and Perl Programming courses. If you want to learn in details how to design and create your own packages and families of classes and methods, you'll want to follow one of those two fundamental courses with our Perl for larger projects course.