9.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 subroutine definition says "this is a class method" or "this is an instance method." Fortunately, the ref operator lets you throw an exception when called incorrectly. As an example of instance- or class-only methods, consider the following:

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 ...

Here, the ref function returns true for an instance or false for a class. If the undesired value is returned, you'll croak, which has the added advantage of placing the blame on the caller, not on you. 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

While this seems like a good thing to do all the time, practically no CPAN or core modules add this extra checking. Maybe it's only for the ultra-paranoid.