Here's an accessor/mutator that is set up for chaining and will accept undef as a value.
sub foo { my $self = shift; # Set attribute if any args if ( @_ ) { $self->{foo} = shift; #validation is for chumps return $self; } else { return $self->{foo} } die "Whiskey Tango Foxtrot"; } # cotrast with this version, which I think you had in mind sub undefoo { my $self = shift; my $newfoo = shift; if ( defined $newfoo ) { $self->{foo} = $newfoo; # What, me validate input? return $self; } else { return $self->{foo}; } die "Whiskey Tango Foxtrot"; }
print $obj->foo(undef), "\n"; # Prints object stringification print $obj->undefoo(undef), "\n"; # prints a "\n"
I don't know how I feel about chaining mutators. I like accessor/mutators that always return the attribute value.
TGI says moo
In reply to Re^3: Method Chaining and Accessors
by TGI
in thread Method Chaining and Accessors
by linenoise
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |