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 .



Learning Perl Objects, References & Modules
Learning Perl Objects, References, and Modules
ISBN: 0596004788
EAN: 2147483647
Year: 2003
Pages: 199

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net