| |
| Recipe 3.12: Creating Autovivifying Attributes and Methods |
Last Updated: Sep 8, 2003
Status: Draft
|
|
|
|
How important is this problem to you?
(Login to Vote)
3.00 Rating, 2 Votes
|
|
How acceptable is the proposed solution?
(Login to Vote)
0.00 Rating, 0 Votes
|
|
Problem:
 
You want to declare that users may call undeclared attributes or methods on a class, and that those attributes and methods should be autovivified in object instances if and when they are called.
Solution:
Use the is autovivifying property.
class MyClass is autovivifying;
my $obj = MyClass.new;
$obj.foo = 5; # if 'foo' doesn't exist, it will be created
Discussion:
The is autovivifying property is a convenient shorthand for declaring that it's acceptable to access attributes and methods of the class that don't actually exist. (You could create similar behavior using AUTOLOAD, but this way is easier.)
- If a nonexistant attribute is requested,
undef will be returned.
- If a nonexistant method is called, it will be interpreted as a null method, and
undef will be returned.
- If a nonexistant attribute is altered, it will be created, and the given value will be returned.
- If a nonexistant method is altered, it will be created using the given anonymous method and signature, and a reference to the anonymous method will be returned.
The is autovivifying property is inherited by subclasses.
Issue:
Is there an easier-to-type property name, rather than is autovivifying?
Issue:
Should is autovivifying be the default state of a class, and we use is strict or similar to get the more stringent behavior?
|
|