locked_user sundialsvc4 has asked for the wisdom of the Perl Monks concerning the following question:
There are certain attributes in my classes for which I would like to generically specify that “assigning undef to these attributes should instead set them to an empty-string.” I know how to do this with an around modifier for the (list of) accessors, but it seems to me that there should be a more-clever way to do that. Is there any kind of trait or role or what-have-you that will let me specify this behavior on a per-attribute basis?
Here is “clunky code” to do what I want: (with the wantarray bit being unimportant; see #MAGICK HERE for the exact spell I want to cast)
around [qw(attr1 attr2 attr3)] => sub { my $orig = shift; my $self = shift; if (wantarray) { my @array_result = $self->$orig(@_); return @array_result; } else { my $scalar_result = $self->$orig(@_); $scalar_result = '' unless defined($scalar_result); #MAGICK HERE return $scalar_result; } };
Notice incidentally that this code actually allows an undef to be stored but presents an empty-string as the result of either a getter or a setter. The exact details are perhaps less important than the notion that I would like to be able to apply behaviors like this to around several accessors (regardless of their names). Without writing clunky code for each one. It just seems to me that there ought to be a very clever way to do this ...
UPDATE: As the following threads will show, my initial guesses that a type-constraint and type-coercion ought to be the solution ... were correct. But I overlooked the necessity of telling Moose to actually do the coercion. (And, yeah, the documentation to that effect.) “So now, Gentle Reader, you know.” Meanwhile, read on . . .
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Moose trait (?) to set "undef" to, say, "empty string?"
by ikegami (Patriarch) on Nov 29, 2011 at 04:04 UTC | |
|
Re: Moose trait (?) to set "undef" to, say, "empty string?"
by locked_user sundialsvc4 (Abbot) on Nov 29, 2011 at 13:27 UTC | |
by Your Mother (Archbishop) on Nov 29, 2011 at 14:18 UTC | |
by locked_user sundialsvc4 (Abbot) on Nov 29, 2011 at 15:39 UTC | |
by ikegami (Patriarch) on Nov 29, 2011 at 14:34 UTC | |
by locked_user sundialsvc4 (Abbot) on Nov 29, 2011 at 15:32 UTC | |
|
Re: Moose trait (?) to set "undef" to, say, "empty string?"
by Anonymous Monk on Nov 30, 2011 at 03:16 UTC | |
by locked_user sundialsvc4 (Abbot) on Nov 30, 2011 at 03:17 UTC |