This is where getting perl to do it in perl 6 is going to be cleaner...
$obj->color(undef);
Does this set the color to undef? Perhaps you mean:
my $code = sub {
my $self = shift;
$self->{$attribute} = shift if @_;
$self->{$attribute};
}
(Falling off rather than returning is just a tiny bit faster according to the benchmarks I've done in the past.) Here, if you pass anything in, it'll get set, but we won't set to undef if you don't pass anything in. Your original is ok if undef is the sole invalid value. That is actually more rare than some people may think - in true perl fashion, by allowing anything, you leave your code more flexible. The primary exceptions are generally external standards, and, even then, should only be when you're outputting them, not interpreting them on input. That is, be conservative in what you send (stick to the letter of the standard), but liberal in what you receive (allow variations on the input). For get/set methods, I find it extremely rare that I don't want the ability to set a variable to undef to signify its invalid or unknown state. For example, setting color to undef simply means that, at this point in the program, I don't know the color, even if I thought I did earlier.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|