Perl Example #9
Classes, Objects, and Perl Modules

About the Program

This program demonstrates how to define a class called Student, with its associated methods or functions. These routines are defined in an external Perl Module called StudentRec.pm.

The regular program, ex9.pl, sets up an array of record-like structures. The Constructor for this class calls the method new, which establishes a reference to an object of the class type. The function new then calls initialize which either assigns initial values that were passed as parameters, or else assigns default values. Later, elements in the array are modified using the method Modify, or printed using PrintRec.

The typical output one would expect is printed in red. A few additonal lines of output, printed in blue, are used to better understand what is happening in the Perl Module. Such debugging output would not normally appear in the final program.

The External Perl Module:     StudentRec.pm


package Student;  # Class Definition for Object of type Student

@student_data = qw(Name ID GPA ); # Name the fields

### The subroutines "new" and "initialize" for the Constructor

sub new   
{
	print "new: @_ \n";
        my $class_name = shift;		# Gets class name from parmlist

        my $recref = {};		# Creates reference to object

        bless $recref, $class_name;     # Associates reference with class

        $recref -> initialize(@_);      # Call local initialize subroutine
					#   passing rest of parmlist

        return $recref;                 # Explicit return of value of $recref
}

sub initialize
{
	print "initialize: @_ \n";
        my $stu_ref = shift;    # Receive an object reference as 1st param
        my %parms = @_;         # Get passed parameters from the call to "new"

        # Change hash reference for key with supplied value, or assign default
        $stu_ref -> {'Name'}        = $parms{'Name'}    ||   "NOBODY";
        $stu_ref -> {'ID'}          = $parms{'ID'}      ||   "NO_ID";
        $stu_ref -> {'GPA'}         = $parms{'GPA'}     ||    0;
}


sub PrintRec  # Print a student record
{
      
	print "PrintRec: @_ \n";
        my $instance = shift;  # Figure out who I am

        for(@student_data)     # Go through all fields
        {
                print "$_: ", $instance -> {$_}, "\n"; # Print key and value
        }
}


sub Modify  #  Modify student Record
{
	print "Modify: @_ \n";
        my $instance = shift; # Figure out who I am
        my %parms = @_;       # Make hash out of rest of parm list

	# Step through all keys in parm list
        for(keys %parms)  
        {
                $instance -> {$_} = $parms{$_}; # Replace with new value 
        }
}


1;		# Return 1 to say Perl Module loaded correctly


The Program:     ex9.pl

#!/usr/bin/perl -w ### This program deals with an array of records. The records are objects ### of type Student, which are defined in Perl Module called StudentRec.pm require StudentRec; # Allows program to use items defined in Perl Module ### subroutine to print out records in an Array sub print_kids { my $kid; foreach $kid (@person) { PrintRec $kid; # Call method "PrintRec" defined for class Student print "\n"; } } #### Initialize Array of Records #### ## Method "new" creates an object of type Student, and then passes ## parameters onto an initialization routine. One would usually ## initialize from a file rather than direct assignment, however. # This Record is defined in typical order (Name, ID, GPA) $person[0] = new Student( 'Name' => "Bill", 'ID' => "12-345-6", 'GPA' => 3.8); # No fields are defined for this record - Constructor uses defaults $person[1] = new Student; # Fields may be defined in any order since the record is a hash $person[2] = new Student( 'GPA' => 4.0, 'Name' => "Hillary", 'ID' => "98-765-4");

new: Student Name Bill ID 12-345-6 GPA 3.8
initialize: Student=HASH(0x10023180) Name Bill ID 12-345-6 GPA 3.8

new: Student
initialize: Student=HASH(0x10023198)

new: Student GPA 4 Name Hillary ID 98-765-4
initialize: Student=HASH(0x100231b0) GPA 4 Name Hillary ID 98-765-4



# Print out details
print "Before...\n";

print_kids;




Before...
PrintRec: Student=HASH(0x10023180)
Name: Bill
ID: 12-345-6
GPA: 3.8

PrintRec: Student=HASH(0x10023198)
Name: NOBODY
ID: NO_ID
GPA: 0

PrintRec: Student=HASH(0x100231b0)
Name: Hillary
ID: 98-765-4
GPA: 4

#### Change things a bit  ####

# Add new person. Undefined fields take the default values
$person[3] = new Student('Name' => "Monica");

# Call Modify method in package
$person[0] -> Modify('GPA'  => 1.6);  # Pass key and value in parm list 




new: Student Name Monica
initialize: Student=HASH(0x10023210) Name Monica

Modify: Student=HASH(0x10023180) GPA 1.6

print "After...\n";

print_kids;




After...
PrintRec: Student=HASH(0x10023180)
Name: Bill
ID: 12-345-6
GPA: 1.6

PrintRec: Student=HASH(0x10023198)
Name: NOBODY
ID: NO_ID
GPA: 0

PrintRec: Student=HASH(0x100231b0)
Name: Hillary
ID: 98-765-4
GPA: 4

PrintRec: Student=HASH(0x10023210)
Name: Monica
ID: NO_ID
GPA: 0

The actual program: ex9.pl

The Perl Module: StudentRec.pm

The output: ex9.out

dhyatt@thor.tjhsst.edu