Learning Object Orientation in Perl through bananas and perhaps Moose
Archive - Originally posted on "The Horse's Mouth" - 2010-12-21 08:18:24 - Graham Ellis
Perl has the most incredbible range of OO facilities (though at times it's overfeatured and a bit old fashioned / tricky to use). So yesterday I wrote a whole series of examples ... and then went on to explore Moose - a module which adds extra keywords and lets you define your classes in a shorter and somewhat more conventional way. See [here] for the moose series - this post introduces the standard facilities in a series of examples.
Bananas.
Our supplier for the hotel provides three types - best bananas, large bananas and small bananas ... "best" are priced per kg, "large" per fruit, and "small" per bunch ... which makes life interesting when we do stock controls and start looking at supply usage, but it did provide a very useful example for yesterday ...
Here are the examples
Setting up a package of hash references - [source]
How to bless the references and thus turn them into objects - [source] - First practical example
Notifying the caller of where errors are triggered in his code via carp, croak and confess - [source]
Use of the caller function to examine the stack frames - [source]
Base class, subclasses, inheritance - [source]First example that shows how we do polymorphism in Perl
How we can use the Universal superclass to find out what our object is / what it can do - [source]can lead to poor class design!
A factory method to construct objects indirectly - [source]
Perl 5's OO facilities are covered on our Perl for Larger Projects course - where we cover OO principles too as necessary. Moose can be introduced on private courses (it's a bit of an interim thing prior to Perl 6 though), or if you're on the public course let me know you would like to cover it and I'll run an extra session one evening.