3 ms·
Speaking of ridiculously verbose, if they're going to pull in Moose to do OO in Perl they could at least use it's ability to provide default arguments instead o
by grncdr 15y ago
Speaking of ridiculously verbose, if they're going to pull in Moose to do OO in Perl they could at least use it's ability to provide default arguments instead of abusing BUILDARGS:
package Int;
use Moose;
has 'value' => ( is => 'rw', isa => 'Int', default => 0 );
no Moose;
Of course, Moose (while awesome) is hardly the only approach to OO in Perl:
package Int;
sub new {
my $cls = shift;
$cls = ref($cls) || $cls;
my $val = shift or 0;
bless \$val, $cls;
}
sub getValue { ${$_[0]} }
1;
Rather than wrapping the scalar int inside another data structure to be treated as an "object" it's possible to just take a reference and use that as our object. So in this case getValue is really just a verbose way to dereference ($int->getValue vs. $$int).
If you don't care about inheritance you could also take out the first two lines of ``new`` and just have:
package Int;
sub new { bless \($_[0] or 0) }
sub getValue { ${$_[0]} }
1;
Disclaimer: this kind of code is usually considered terrible Perl style and why people have such a hang up about the language, don't take this as idiomatic
Edit: Just noticed that they seem to think instance variables in Perl are private by default. Not sure where they got that idea? I guess Moose attributes are read-only by default, but that's hardly the same thing.