You have already learned that a static method is one that can be called without needing an instantiated object. Actually, you can also have static variables as you saw in the last section. Static variables can be used to emulate constants, values that don't change. Constants are very useful. For example, you can use them for tax rates, mathematical constants, and things such as state abbreviations. Here is an example using a small Perl script, static.pl:
package Math; $math{'PI'} = 3.1415; package main; print("The value of PI is $Math::math{'PI'}.\n");
This program displays:
The value of PI is 3.1415.
You can also do this:
package Math; $PI = 3.1415; package main; print("The value of PI is $Math::PI.\n");
Because you have been using a static method all along-the new() method -- let's demonstrate a regular function.
The following code shows how to use the UNIVERSAL package to define a utility function that is available to all classes.
The Perl Code for this is stat_univ.pl:
package UNIVERSAL; sub lookup { return(%{$_[0]}->{$_[1]}); } package Inventory_item; sub new { my($class) = shift; my(%params) = @_; my($self) = { }; $self->{"PART_NUM"} = $params{"PART_NUM"}; $self->{"QTY_ON_HAND"} = $params{"QTY_ON_HAND"}; return(bless($self, $class)); } package main; $item = Inventory_item->new("PART_NUM"=>"12A-34", "QTY_ON_HAND"=>34); print("The part number is " . $item->lookup('PART_NUM') . "\n"); print("The quantity is " . $item->lookup('QTY_ON_HAND') . "\n");
Finally, the printAll() function shown here displays all the properties of a class, or you can specify one or more properties to display printAll.pl:
sub printAll { my($self) = shift; my(@keys) = @_ ? @_ : sort(keys(%{$self})); print("CLASS: $self\n"); foreach $key (@keys) { printf("\t%10.10s => $self->{$key}\n", $key); } }
If you put this function into the UNIVERSAL package, it will be available to any classes you define.
After constructing an inventory object, the statement $item->printAll(); might display
CLASS: Inventory_item=HASH(0x77ceac) PART_NUM => 12A-34 QTY_ON_HAN => 34
and the statement
$item->printAll('PART_NUM');
might display
CLASS: Inventory_item=HASH(0x77ceac) PART_NUM => 12A-34