Determining Subclass Membership

Problem

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

Solution

Use 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

Discussion

Wouldn’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 @ISA. Well, you can. You don’t see it, but Perl pretends there’s an extra element at the end of @ISA—the package named UNIVERSAL.

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 isa , can, and VERSION. The isa method tells you whether an object or class “is” another one, without having to traverse the hierarchy yourself:

$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 can method, called on behalf of that object or class, reports back whether its string argument ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.