This section provides a tutorial example of a simple Perl class, CalendarClass with new() method, class variables, and some set*() and get*() object methods.
Here is another class, CalendarClass.pm, that shows you how to define class methods, object
methods and object creation method:
#- CalendarClass.pm
#- Copyright (c) 1999 by Dr. Herong Yang, http://www.herongyang.com/
#
package CalendarClass;
sub BEGIN {
$author = "Dr. Herong Yang";
$version = "1.00";
$info = "My first Perl class.";
}
sub new {
my $this = shift;
my $class = ref($this) || $this;
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$x) = localtime();
my $self = {};
$$self{"SEC"} = $sec;
$$self{"MIN"} = $min;
$$self{"HOUR"} = $hour;
$$self{"MDAY"} = $mday;
$$self{"MON"} = $mon + 1;
$$self{"YEAR"} = $year + 1900;
return bless $self;
}
sub getDate {
my $this = shift;
return $$this{"MON"}.'/'.$$this{"MDAY"}.'/'.$$this{"YEAR"};
}
sub getTime {
my $this = shift;
return $$this{"HOUR"}.":".$$this{"MIN"}.":".$$this{"SEC"};
}
sub setYear {
my $this = shift;
$$this{"YEAR"} = shift;
}
sub getAuthor {
return $author;
}
sub getVersion {
return $version;
}
sub getInfo {
return $info;
}
1;
Here is a program to test the CalendarClass class:
#- CalendarClassTest.pl
#- Copyright (c) 1999 by Dr. Herong Yang, http://www.herongyang.com/
#
use CalendarClass;
$c = CalendarClass->new();
print("\nTest 1:\n");
print(" Date and time: ",$c->getDate()," ",$c->getTime(),"\n");
$c->setYear("2000");
print(" Date and time: ",$c->getDate()," ",$c->getTime(),"\n");
print("\nTest 2:\n");
print(" Year: ",$$c{"YEAR"},"\n");
print(" Year: ",$c->{"YEAR"},"\n");
print("\nTest 3:\n");
print(" Author: ",CalendarClass->getAuthor(),"\n");
print(" Version: ",CalendarClass::getVersion(),"\n");
print(" Info: ",$c->getInfo(),"\n");
exit;
Output:
Test 1:
Date and time: 12/20/1999 23:53:57
Date and time: 12/20/2000 23:53:57
Test 2:
Year: 2000
Year: 2000
Test 3:
Author: Dr. Herong Yang, http://www.herongyang.com/
Version: 1.00
Info: My first Perl class.