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

Using Named Parameters in Constructors

The concept of using named parameters has been quickly accepted in new computer languages. I was first introduced to it while working with the scripting language for Microsoft Word. Rather than explain the technique in words, let's look at an example in code, as shown below:

The code listing invent.pl is as follows:

package Inventory_item;

    sub new {

        my($class)  = shift;

        my(%params) = @_;



        bless {

            "PART_NUM"    => $params{"PART_NUM"},

            "QTY_ON_HAND" => $params{"QTY_ON_HAND"}

            }, $class;

    }



package main;



    $item = Inventory_item->new(

"PART_NUM"    => "12A-34",

"QTY_ON_HAND" => 34);



    print("The part number is " . %{$item}->{'PART_NUM'} . "\n");

    print("The quantity is " . %{$item}->{'QTY_ON_HAND'} . "\n");

One key statement to understand is the line in which the new() function is called:

$item = Inventory_item->new(

"PART_NUM"    => "12A-34",

               "QTY_ON_HAND" => 34);

This looks like an associative array is being passed as the parameter to new(), but looks are deceiving in this case. The => operator does exactly the same thing as the comma operator. Therefore, the preceding statement is identical to the following:

$item = Inventory_item->new("PART_NUM", "12A-34", "QTY_ON_HAND", 34);

Also, a four-element array is being passed to new().

The second line of the new() function, my(%params) = @_; does something very interesting. It takes the four-element array and turns it into a hash with two entries. One entry is for PART_NUM, and the other is for QTY_ON_HAND.

This conversion (array into hash) lets you access the parameters by name using %params. The initialization of the anonymous hash-inside the bless() function-takes advantage of this by using expressions such as $params{"PART_NUM"}.

I feel that this technique helps to create self-documenting code. When looking at the script, you always know which property is being referred to. In addition, you can also use this technique to partially initialize the anonymous hash. For example,

$item = Inventory_item->new("QTY_ON_HAND" => 34);

gives a value only to the QTY_ON_HAND property; the PART_NUM property will remain undefined. You can use this technique with any type of function, not just constructors.


next up previous contents
Next: Inheritance: Perl Style Up: Objects in Perl Previous: Initializing Properties
dave@cs.cf.ac.uk