|
perlobj - Perl Objects
Part:
1
2
3
4
5
(Continued from previous part...)
I used both syntaxes in the followiwng sample program, ObjectMethodTest.pl:
#- ObjectMethodTest.pl
#- Copyright (c) 1999 by Dr. Herong Yang
#
package Foo;
sub echoParam {
$i = 0;
while ( $p = shift) {
$i++;
print(" Param #",$i," = ",$p,"\n");
}
}
package main;
$m = "Hello world!";
$r = \$m;
$x = bless($r,Foo);
print("\nCheck data types:\n");
print(" Type of \$n: ",ref($n),"\n");
print(" Type of \$r: ",ref($r),"\n");
print(" Type of \$x: ",ref($x),"\n");
print(" \$x == \$r\n") if ($x==$r);
print("\nTest 1:\n");
echoParam $x "Fire", "Water";
# print("\nTest 2:\n");
# &echoParam $x "Fire", "Water";
# print("\nTest 3:\n");
# echoParam $m "Fire", "Water";
print("\nTest 4:\n");
$x->echoParam("Java", "Perl");
exit;
Output:
Check data types:
Type of $n:
Type of $r: Foo
Type of $x: Foo
$x == $r
Test 1:
Param #1 = Foo=SCALAR(0x1ab2f54)
Param #2 = Fire
Param #3 = Water
Test 4:
Param #1 = Foo=SCALAR(0x1ab2f54)
Param #2 = Java
Param #3 = Perl
Note that:
- It is true that you can bless any reference into an object.
In my sample program, I blessed a reference of the scalar into
an object of class "Foo".
- Tests 1 and 4 are special ways to invoke a subroutine as an object method.
- Test 2 is wrong, because "&" is not allowed.
- Test 3 is wrong, because "$m" is not an object.
Using Package Level Variables as Class Variables
In Perl, all package level variables are class variables. There is no private
variable concept in Perl. All variables are publicly accessible in the
same way as package variables.
Using Hash Entries to Store Object Variables
As you can see the previous section, you can bless a reference of any "thing"
into an object of a specific class.
In order to define object variables, we must create objects with references
of the same data type for the same class. Using references of differenct data
types for the same class will cause confusion to class and object methods.
The number and type of object variables
you can use depend on the data type you select for the references:
- If you use references of scalars, you can only have one object variable.
- If you use references of arrays, you can have many un-named object variables.
- If you use references of hashs, you can have many named object varibles.
Of course, hash is the best choice to host object variables.
Since objects are references, accessing object variables can be done in the
same way as accessing references.
Here is a sample program to show you how to handle class variables and object
variables:
(Continued on next part...)
Part:
1
2
3
4
5
|