This section provides a tutorial example on how to new() method to create objects inside the class. A typical new() method will create a reference of an anonymous hash with initial keys and values, then bless it to an object.
As you can see from the sample program, ObjectVariableTest.pl, objects are
created and initiated in the calling package. This is not a safe approach,
because the calling package could initialize the object with incorrect hash keys.
A better approach is for the class itself to offer a method to create objects
and possibly initialize them. This method is usually called new().
So I improved my program by adding the new() method in the Account class.
Notice that I have to create a reference to an anonymous hash in the new() method,
so that each call of new() will get a reference (blessed into an object) of
a new hash.
#- AccountClassTest.pl
#- Copyright (c) 1999 by Dr. Herong Yang, http://www.herongyang.com/
#
package Account;
$euroRate = 0.85;
sub new {
my $class = shift;
$this = {};
$$this{"Name"} = shift;
$$this{"Type"} = shift;
$$this{"Balance"} = shift;
return bless($this,$class);
}
sub print {
my $this = shift;
my $currency = shift;
my $balance = $$this{"Balance"};
$balance *= $euroRate if ($currency eq "EURO");
print("Printing account...\n");
print(" Name = ",$$this{"Name"},"\n");
print(" Type = ",$$this{"Type"},"\n");
print(" Balance = ",$balance,"\n");
}
sub deposit {
my $this = shift;
my $amount = shift;
$$this{"Balance"} += $amount;
}
sub setEuroRate {
my $class = shift;
$euroRate = shift;
}
package main;
$myObj = Account->new("Herong Yang","Checking",100.00);
$hisObj = Account->new("Mike Clinton","Saving",999.00);
print("\nTest 1:\n");
$myObj->print();
$hisObj->print();
print("\nTest 2:\n");
$myObj->deposit(-25.00);
$hisObj->deposit(99.00);
$myObj->print();
$hisObj->print();
print("\nTest 3:\n");
$myObj->print("EURO");
$hisObj->print("EURO");
print("\nTest 4:\n");
Account->setEuroRate(0.80);
$myObj->print("EURO");
$hisObj->print("EURO");
exit;
The output is the same as ObjectVariableTest.pl in the previous section, but now the main package is
completely not aware how the objects are created, and what variables are there
in each objects. Everything is hiding behind the objects.