User Tools

Site Tools


perl:prototype_class_for_oo

Awesome.pm:

package Awesome;
 
use strict;
 
# static (class-wide) variable
my $object_count = 0;
 
# constructor -- a static method that creates and returns a new object
sub new {
	my $class = shift;
	# remaining args are constructor parameters.  
	# we'll assume it takes one param: name.  this parameter gets saved in our new "object", a blessed hash ref
	my $self = {name => $_[0]};
	bless($self,$class);
	$object_count++; # increment a static counter
	return $self;
}
 
# static method -- the first arg is assumed to be the class name (though it could still be called with an object)
sub count_objects_created {
	shift; # discard class
	# remaining args are parameters
	return $object_count;
}
 
# instance method -- first arg is an object (though it can still be called (erroneously) as a static method)
sub do_stuff {
	my $self = shift;
	# ...
	$self->{stuff} = 'done'; # set an instance variable
}
 
# accessor/mutator instance method -- run $obj->name() to read, $obj->name("newvalue") to write
sub name {
	my $self = shift;
	if (@_) { $self->{name} = $_[0]; }
	return $self->{name};
}
 
1;  # so the require or use succeeds

Example use:

#!/usr/bin/perl
 
use strict;
use Awesome;
 
my $obj = Awesome->new("bob");
$obj->name("superbob");
$obj->{name} = "secret bob"; # direct access possible, but unadvisable
my $n = Awesome->count_objects_created();
$obj->do_stuff();
perl/prototype_class_for_oo.txt · Last modified: 2010/01/08 13:52 by tkbletsc