see-if-a-perl-object-has-a-method

Where I work, a lot of perl objects get passed around in all sorts of ways. Functions aren't expected to accept only one class of object -- they're supposed to do the best with what they have. Very "Lisp-y."

You'll frequently see code like this that uses the 'can' function of Perl objects:

for my $listener (@{$self->listeners}) {
  if ($listener->can('on_start')) {
    $listener->on_start($r);
  }
}

which is pretty neat. The "listeners" array contains a list of heterogeneous objects and the loop checks each one -- if the object has an on_start member, this loop will call it.

I'm not sure how expensive "can" is. If "can" is expensive, it would be wise to check the object once before inserting it into the "listeners" array. In this particular case though, we only have one array for multiple callbacks. For instance, there's another loop like:

for my $listener (@{$self->listeners}) {
  if ($listener->can('on_finish')) {
    $listener->on_finish($r);
  }
}

Anyway, using "can" is a quick way of checking if your object has a method you can call.


Follow on Twitter


LinkedIn
Facebook
Notchup, Member 74311




Copyright (C) 2008, Mike McCreavy
[ x ] Console
Timestamp Message
hey
[ x ] Socket Console
Timestamp Message
hey