in reply to Re: Answer: How can I use AUTOLOAD to magically define get and set methods for my member data?
in thread How can I use AUTOLOAD to magically define get and set methods for my member data?

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.

  • Comment on Re^2: Answer: How can I use AUTOLOAD to magically define get and set methods for my member data?
  • Select or Download Code