Object-oriented programming I

#!/usr/local/bin/perl
#########################################
package Student;
sub new {
my $self = {};
bless $self;
$self->{name} = $_[1];
$self->{courses} = $_[2];
return $self;
}
sub printDetails {
my $self = $_[0];
print "Name: $self->{name}\n";
print "Courses: @{$self->{courses}}\n";
}
sub enroll {
my $self = $_[0];
my $course = $_[1];
push (@{$self->{courses}},$course);
}
#########################################
package main;
my($student1) = new Student("Fred", ["L548"]);

print "Input the courses which $student1->{name} is enrolled in.\n";
print "When finished, type X.\n";
$newcourse = <STDIN>;
chomp $newcourse;

while ($newcourse !~ /x/i) {
$student1->enroll($newcourse);
$newcourse = <STDIN>;
chomp $newcourse;
}

$student1->printDetails();

Exercises

Add further attributes to the student class (phone number, email address, degree, etc).

Create an array of students. Let users add new students to the array. Ask the user for the name of a student and then print his/her details.

Create a method creditHours that computes the number of credit hours for a student assuming that every class is a three credit class.

Create a class Employee that contains information about names, ages and positions. What could be useful methods for the class?

Note:

Without blessing the variable in the subroutine "new", a different notation would have to be used:
Student::printDetails($student1);
instead of
$student1->printDetails();
Using that notation any subroutine from any package can be included in a script. A blessed variable contains an internal pointer to its package, i.e. the variable becomes an "object" of that class.

Optional Materials:

The following examples provide more details for the notation (implementation) of object-oriented programming in Perl.

Pointers (references)

#!/usr/local/bin/perl

# normal hash
%hash = ("name", "Fred", "color", "white");
print "$hash{name}\n";
print "$hash{color}\n";

# pointer to a hash
$pointer_to_hash = \%hash;
print "$pointer_to_hash->{name}\n";
print "$pointer_to_hash->{color}\n";

Returning a pointer to a hash from a subroutine

The hash is defined as "$self = {...}" instead of as "%self =(...)". "$self" is a scalar and therefore a pointer to a hash.

#!/usr/local/bin/perl

sub new {
my $self = {};
$self->{'name'} = $_[0];
$self->{'color'} = $_[1];
return $self;
}

my($cat) = new("Fred","white");
print "$cat->{name}\n";
print "$cat->{color}\n";