Herong's Tutorial Notes on Perl - Part A
Dr. Herong Yang, Version 4.09

perlobj - Perl Objects

Part:   1  2   3  4  5 

(Continued from previous part...)

Output:

Test 1:
   Param #1 = Jan
   Param #2 = Feb

Test 2:
   Param #1 = Apple
   Param #2 = Banana

Test 3:
   Param #1 = One
   Param #2 = Two

Test 4:
   Param #1 = Foo
   Param #2 = Cow
   Param #3 = Horse

Test 7:
   Param #1 = Foo
   Param #2 = Monday
   Param #3 = Tuesday

Note that:

  • Tests 1, 2 and 3 are normal ways to invoke a subroutine in a package.
  • Tests 4 and 7 are special ways to invoke a subroutine as a class method.
  • Test 5 is wrong, because "&" is not allowed.
  • Tests 6 and 8 are wrong, because "Bar" is not recognized as a class (package).

Invoking Package Subroutines as Object Methods

In order to use references (hard references, not soft references) as objects of a class, we need to associate references with a class first. This is done by using the bless() funtion in one of the following syntaxes:

   $rc = bless($reference, class_name);
   $rc = bless($reference);

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.

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() function:

   $rc = ref($object);

Similar to class method invocation, if a subroutine is invoked as an object method, the object (blessed reference) will be automatically inserted into the argument list as the first argument. There are two way to invoke a subroutine as a class method:

1. Using the "indirect object" syntax:

   sub_identifier $object arg2, arg3, ...

where "sub_identifier" is the subroutine identifier without any package name prefixes and "&"; "$object" is a blessed object; and "arg2, arg3, ..." is the argument list starting from the second argument without parentheses.

2. Using the "->" notation:

   $object->sub_identifier(arg2, arg3, ...)

where "sub_identifier" is the subroutine identifier without any package name prefixes and "&"; "$object" is a blessed object; and "arg2, arg3, ..." is the argument list starting from the second argument. In this format, parentheses on the argument list are optional.

(Continued on next part...)

Part:   1  2   3  4  5 

Dr. Herong Yang, updated in 2006
Herong's Tutorial Notes on Perl - Part A - perlobj - Perl Objects