Attached is a patch that allows other perl data to be used
as a default value for an attribute besides scalars.
diff -ru lib/Class/Std.pm~ lib/Class/Std.pm
--- lib/Class/Std.pm~ 2005-08-01 18:19:20.000000000 -0700
+++ lib/Class/Std.pm 2005-08-01 17:56:27.000000000 -0700
@@ -343,7 +343,12 @@
}
# Or use default value specified...
- $attr_ref->{ref}{$new_obj_id} = $attr_ref->{default};
+ $attr_ref->{ref}{$new_obj_id} = eval $attr_ref->{default};
+
+ if ($@) {
+ $attr_ref->{ref}{$new_obj_id} = $attr_ref->{default};
+ }
+
next INIT if defined $attr_ref->{ref}{$new_obj_id};
if (defined $attr_ref->{init_arg}) {
@@ -1379,6 +1384,10 @@
# No BUILD() required
+Note that any valid perl datatype can be used for the default
+value:
+
+ my %customers_of :ATTR( :default([]) );
=item C<< :ATTR( :get<name> ) >>
diff -ru t/simple.t~ t/simple.t
--- t/simple.t~ 2005-05-15 20:58:24.000000000 -0700
+++ t/simple.t 2005-08-01 18:20:15.000000000 -0700
@@ -1,13 +1,20 @@
-use Test::More 'no_plan';
+use Test::More tests => 48;
package MyBase;
use Class::Std;
{
- my %name : ATTR( :init_arg<name> :get<name> );
- my %rank : ATTR( init_arg => 'rank' :get<rank> :set<rank> );
- my %snum : ATTR( :init_arg('snum') :get<snum> );
- my %priv : ATTR;
- my %def : ATTR( :default<MyBase::def> :get<default> );
+ my %name : ATTR( :init_arg<name> :get<name> );
+ my %rank : ATTR( init_arg => 'rank' :get<rank> :set<rank> );
+ my %snum : ATTR( :init_arg('snum') :get<snum> );
+ my %priv : ATTR;
+ my %def : ATTR( :default<MyBase::def> :get<default> );
+ my %scalar : ATTR( :default<\""> );
+ my %array : ATTR( :default<[]> );
+ my %hash : ATTR( :default<{}> );
+ my %code : ATTR( :default<sub {}> );
+ my %ref : ATTR( :default<\\*glob> );
+ my %glob : ATTR( :default<\*glob> );
+ my %regexp : ATTR( :default<qr//> );
sub BUILD {
my ($self, $ident, $arg_ref) = @_;
@@ -37,6 +44,14 @@
::is $snum{$ident}, 'MyBase::snum!' => 'MyBase::snum initialized';
::is $priv{$ident}, 'MyBase::priv' => 'MyBase::name initialized';
::is $def{$ident}, 'MyBase::def' => 'MyBase::def initialized';
+
+ ::is ref $scalar{$ident}, 'SCALAR' => 'MyBase::scalar initialized';
+ ::is ref $array{$ident}, 'ARRAY' => 'MyBase::array initialized';
+ ::is ref $hash{$ident}, 'HASH' => 'MyBase::hash initialized';
+ ::is ref $code{$ident}, 'CODE' => 'MyBase::code initialized';
+ ::is ref $ref{$ident}, 'REF' => 'MyBase::ref initialized';
+ ::is ref $glob{$ident}, 'GLOB' => 'MyBase::glob initialized';
+ ::is ref $regexp{$ident}, 'Regexp' => 'MyBase::regexp initialized';
}
}