CGI and Perl

Listing 2.7. Using the MyCust subclass.

use MyCust; # requires both and to be @INC
 # Create a new customer object
 $cust  = MyCust->new( `Name' => "Billy T. Kid",
         `Vitals' => ["Age : 10", "Sex : M"] );
 # add a single statistic
 $cust->addstat(`Phone' => `1-203-456-7890');
 # search for and return the phone number
 print "Customer's phone number is ",$cust->search(`Phone'),"\n";
 # prints:
 Customer's phone number is 1-203-456-7890

Simple, fast, easy, and fun. In Listing 2.7, you've just used the object-oriented programming technique called inheritance. Hopefully, the usefulness and simplicity of object-oriented programming techniques are now easier to understand and believe in, if you haven't seen them before. Method Override and Method Augmentation Another powerful object-oriented technique is known as method override. Suppose that instead of needing to add an additional method to Customer, you need for an existing method in the module to behave in a different way. Well, because I've discussed the alternatives already, I'll assume that you want to implement the new behavior in the object-oriented way. The technique is very much like the preceding inheritance example, but this time you name your method the same as the method that you want to behave differently.

The dumpcust method within Customer, for instance, is not very useful if you add additional fields to the customer object using addstat. You can override it with something a bit more generic, as shown in Listing 2.8.

Listing 2.8. Overriding Customers methods.

package MyCust;
 require Customer; # requires from Listing 2.4
 @ISA = qw(Customer);
 sub search{
 my $self = shift;
 my $key = shift;
 defined($self->{$key}) ? return $self->{$key} : undef;
 sub dumpcust{
 my $self = shift;
 # Print out _all_ the values for the object
 foreach $key (keys %{$self}){
     if($key eq `Vitals'){
         print join(` `,@{$self->{$key}}),"\n";
         print $self->{$key},"\n";

Now you can invoke the dumpcust() method within the MyCust class and get the behavior you want, having all the fields print. (Note that Listing 2.9 requires the code from both Listing 2.4 and 2.8.)