This section provides a tutorial example on how to use the bless() function to convert (bless) hard references to objects of the specified class. References of anonymous values or anonymous functions are not allowed to be blessed.
In order to use references (hard references, not soft references) as
objects of a class (or package), we need to associate references with a class first.
This is done by using the bless() function in one of the following syntaxes:
where "$reference" is a reference of any data type, which will be associated with
the specified "class_name" (package name). "$rc" is the returning copy of
the same reference. If "class_name" is omitted, the current package name will
be used as the class name. bless() can not be used to references of anonymous scalars.
Perl object - A reference that has been blessed with a package name.
To figure out the associated class name of object, you can use the ref($ref) function,
which will return different values:
(class name) - If $ref has been blessed to a class.
SCALAR - If $ref is not blessed and is a reference to a scalar.
ARRAY - If $ref is not blessed and is a reference to an array.
HASH - If $ref is not blessed and is a reference to a hash.
CODE - If $ref is not blessed and is a reference to a function.
In order to test the bless() function and the ref() function,
I wrote this tutorial program:
#- ObjectBless.pl
#- Copyright (c) 1999 by Dr. Herong Yang, http://www.herongyang.com/
#
$x = 1;
$a = \$x; # Creating a reference for a scalar
bless($a, MyClass); # Converting to an object
print ref($a), "\n"; # $a is an object of MyClass
print $a, "\n"; # $a is a reference of scalar variable
print $$a, "\n"; # using $a as reference
print ref(\$x), "\n"; # ?
@y = (Hello);
$b = \@y; # Creating a reference for an array
bless($b, YourClass); # Converting to an object
print ref($b), "\n"; # $b is an object of MyClass
print $b, "\n"; # $b is a reference of array variable
print $$b[0], "\n"; # using $b as reference
print ref(\@y), "\n"; # ?
$c = \(1+1); # Reference to an anonymous scalar
# bless($c, HisClass); # not allowed on anonymous reference
$d = [1,2,3]; # Reference to an anonymous array
bless($d, HisClass); # Converting to an object
print ref($d), "\n"; # $d is an object of HisClass
$e = {Jan,31,Feb,28}; # Reference to an anonymous hash
bless($e, HisClass); # Converting to an object
print ref($e), "\n"; # $e is an object of HisClass
print ref(\$ss), "\n"; # Returning SCALAR
print ref(\@aa), "\n"; # Returning ARRAY
print ref(\%hh), "\n"; # Returning HASH
print ref(\&ff), "\n"; # Returning CODE
print ref(\(1+1)), "\n"; # Returning SCALAR