Main Content

Factory method example - Perl

Archive - Originally posted on "The Horse's Mouth" - 2008-06-04 20:47:37 - Graham Ellis

Utility methods (factorys) are often used to create objects which may be of any of one of a series of different classes, depending on the data passed in. Have a look at this Perl program which reads in data from a log file and creates a list of web site visit objects:

use visit;
 
open (FH,"ac_20080527");
 
while ($line = <FH>) {
  $current = make visit($line);
  push @samples,$current;
}


make visit is actually creating objects of type robot or human - which happen to be subclasses of visit though they don't have to be. Here is the code:

package visit;
sub make {
package visit;
sub make {
  $stuff = $_[1];
  if ($stuff =~ /slurp|crawl|spider|bot/i) {
    return (new robot($stuff));
  } else {
    return (new human($stuff));
  }
}


The result is that the list in the main code ends up containing a list of objects of various types, and using polymorphic methods on those objects, very need code can be used to call in different features of each.

If you want to have a look at the complete source code of both the main application and the visit.pm module, you can open each of them in a separate window here and here. If you want to learn all about OO in Perl (it's great for larger scripting tasks) look at our Perl for Larger Projects Course ... you've just missed one, I'm afraid ... but there will be another one along later this year!