Приглашаем посетить
Html (html.find-info.ru)

Section 12.14.  Restricting a Method to Class-Only or Instance-Only

Previous
Table of Contents
Next

12.14. Restricting a Method to Class-Only or Instance-Only

Setting the name of an unnameable generic Horse is probably not a good idea; neither is calling named on an instance. Nothing in the Perl method definition says "this is a class method" or "this is an instance method." Fortunately, the ref operator lets us throw an exception when called incorrectly. As an example of instance- or class-only methods , consider the following, where we check the argument to see what to do:

use Carp qw(croak);

sub instance_only {
  ref(my $self = shift) or croak "instance variable needed";
  ... use $self as the instance ...
}

sub class_only {
  ref(my $class = shift) and croak "class name needed";
  ... use $class as the class ...
}

The ref function returns true for an instance, which is just a blessed reference, or false for a class, which is just a string. If it returns an undesired value, we use the croak function from the Carp module (which comes in the standard distribution). The croak function places the blame on the caller by making the error message look like it came from the spot where we called the method instead of the spot where we issued the error. The caller will get an error message like this, giving the line number in their code where the wrong method was called:

instance variable needed at their_code line 1234

Just as croak is provided as the alternate form of die, Carp also provides carp as a replacement for warn. Each tells the user which line of code called the code that caused the problem. Instead of using die or warn in your modules, use the Carp functions instead. Your users will thank you for it.


Previous
Table of Contents
Next