ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
13.8. Determining Subclass MembershipProblemYou want to know whether an object is an instance of a particular class or that class's subclasses. Perhaps you want to decide whether a particular method can be called on an arbitrary object. SolutionUse methods from the special UNIVERSAL class: $obj->isa("HTTP::Message"); # as object method HTTP::Response->isa("HTTP::Message"); # as class method if ($obj->can("method_name")) { .... } # check method validity DiscussionWouldn't it be convenient if all objects were rooted at some ultimate base class? That way you could give every object common methods without having to add to each In version 5.003, no methods were predefined in UNIVERSAL, but you could put whatever you felt like into it. However, as of version 5.004, UNIVERSAL has a few methods in it already. These are built right into your Perl binary, so they don't take extra time to load. Predefined methods include $has_io = $fd->isa("IO::Handle"); $itza_handle = IO::Socket->isa("IO::Handle"); Arguably, it's usually best to try the method call. Explicit type checks like this are sometimes frowned upon as being too constraining. The $his_print_method = $obj->can('as_string'); Finally, the Some_Module->VERSION(3.0);
$his_vers = $obj-> However, we don't usually call use Some_Module 3.0; If you wanted to add version checking to your Person class explained above, add this to Person.pm: use vars qw($VERSION);
$VERSION = '1.01'; Then, in the user code say See AlsoThe documentation for the standard UNIVERSAL module; the |