← Back to Perl Course | Chapter 7: Object-Oriented Perl | Lesson 6 of 7

Checking objects: ref, isa and can

Perl can tell you what class an object belongs to and what it can do.

Checking objects: ref, isa and can

ref($obj) returns the class name of a blessed reference. The methods isa and can, which every class inherits from UNIVERSAL, check whether an object is derived from a class and whether it has a given method. can returns a code reference that you can call, or a false value if the method does not exist.

Note: Call isa and can as $obj->isa(Class) only on real objects; on unknown values use Scalar::Util::blessed first.

Example: Checking objects: ref, isa and can

perl
use strict;
use warnings;

package Shape;
sub new { my $class = shift; return bless {}, $class; }
sub area { return 0; }

package Circle;
our @ISA = ('Shape');
sub radius { return 2; }

package main;

my $c = Circle->new;
print "ref: ", ref($c), "\n";
print "isa Circle: ", ($c->isa('Circle') ? "yes" : "no"), "\n";
print "isa Shape: ", ($c->isa('Shape') ? "yes" : "no"), "\n";
print "isa Dog: ", ($c->isa('Dog') ? "yes" : "no"), "\n";
print "can radius: ", ($c->can('radius') ? "yes" : "no"), "\n";
print "can area (inherited): ", ($c->can('area') ? "yes" : "no"), "\n";
print "can volume: ", ($c->can('volume') ? "yes" : "no"), "\n";
if (my $m = $c->can('radius')) {
    print "radius via can: ", $c->$m(), "\n";
}
print "class string can: ", (Circle->can('new') ? "yes" : "no"), "\n";

# Output:
# ref: Circle
# isa Circle: yes
# isa Shape: yes
# isa Dog: no
# can radius: yes
# can area (inherited): yes
# can volume: no
# radius via can: 2
# class string can: yes
Common Mistakes
  1. Comparing ref($obj) with eq and missing subclasses
  2. Calling a method on undef or an unblessed reference
  3. Forgetting that can returns a code reference, not the method's result
Chapter Summary
  • ref returns the class of an object
  • isa checks for the class or its ancestors
  • can checks for a method
  • can returns a code reference
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.