next up previous contents
Next: Initializing Properties Up: Objects in Perl Previous: Objects in Perl

Bless the Hash and Pass the Reference

If you recall from Chapter on refernces the ref() function returns either the undefined value or a string indicating the parameter's data type (SCALAR, ARRAY, HASH, CODE, or REF). When classes are used, these data types don't provide enough information.

This is why the bless() function was added to the language. It lets you change the data type of any variable. You can change the data type to any string value you like. Most often, the data type is changed to reflect the class name.

It is important to understand that the variable itself will have its data type changed. The following lines of code should make this clear (

$foo    = { };

$fooRef = $foo;

print("data of \$foo is "    . ref($foo)    . "\n");

print("data of \$fooRef is " . ref($fooRef) . "\n");

bless($foo, "Bar");

print("data of \$foo is "    . ref($foo)    . "\n");

print("data of \$fooRef is " . ref($fooRef) . "\n");

This program displays the following:

data of $foo is HASH

data of $fooRef is HASH

data of $foo is Bar

data of $fooRef is Bar

After the data type is changed, the ref($fooRef) function call returns Bar instead of the old value of HASH. This can happen only if the variable itself has been altered. This example also shows that the bless() function works outside the object-oriented world.