Perl6 Object Oriented Cookbook (v0.2.1)  
Section 1: Introduction to Object Oriented Perl6  
 
Recipe 1.14: Determining the Existence of an Attribute or Method
Last Updated: Sep 8, 2003
Status: Draft
      Previous Page   Next Page

How important is this problem to you?
  (Login to Vote)
5.00 Rating, 3 Votes  

How acceptable is the proposed solution?
  (Login to Vote)
5.00 Rating, 2 Votes  

Problem:  

You have a class name or an object of unknown type. You want to find out whether or not a foo attribute or method exists in that class or object.

Solution:  

Use the CAN method, made available to every perl6 class:

MyClass.CAN('foo');         # on a class

if ($obj.CAN('foo')) {      # on an object
    $obj.foo;
}

MyClass can 'foo';          # "can" operator; synonymous
$obj can 'foo';

Discussion:

The CAN method takes a name and returns a boolean value indicating whether or not the given object or class has an attribute or method by that name. This allows you to determine if an object has a given capability, without caring what the actual definition of the object may be.

As a shorthand version, the "can" operator functions in a similar manner: given a class name or an object on the left side, it returns whether that class or object has the attribute or method named on the right side.


Log In to Comment


Login / Edit User Info -- Copyright © 2002 Cognitivity -- Previous Page   Next Page