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.
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";