From: Karen Etheridge Date: Fri, 25 Feb 2011 18:03:25 +0000 (-0800) Subject: add example for combining an initializer with a writer - basically the same code... X-Git-Tag: 1.9903~6 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=44c5aa3295358c7f0d33996d80f53f49c2f0fc2a;p=gitmo%2FMoose.git add example for combining an initializer with a writer - basically the same code as in stackoverflow.com/q/5116788/40468 --- diff --git a/lib/Class/MOP/Attribute.pm b/lib/Class/MOP/Attribute.pm index 1603ed5..808cb0f 100644 --- a/lib/Class/MOP/Attribute.pm +++ b/lib/Class/MOP/Attribute.pm @@ -617,8 +617,31 @@ attribute initialization use the writer: ) ); -Your writer will need to examine C<@_> and determine under which -context it is being called. +Your writer (actually, a wrapper around the writer, using +L) will need to examine +C<@_> and determine under which +context it is being called: + + around 'some_attr' => sub { + my $orig = shift; + my $self = shift; + # $value is not defined if being called as a reader + # $setter and $attr are only defined if being called as an initializer + my ($value, $setter, $attr) = @_; + + # the reader behaves normally + return $self->$orig if not @_; + + # mutate $value as desired + # $value = ($row) if $setter; + + # otherwise, call the real writer with the new value + $self->$orig($row); + }; + =back