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 idiomaticEdit: 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.
In contrast to Python, in Ruby all instance member variables are private.
Isn't the whole point of this table to compare equivalent snippets of code? You're right, those languages do things very differently from one another - especially when it comes to OO. In this case, the stated goal was to define a class that exposes a public property. In this I believe PHP and probably Perl were represented badly.
If you don't believe me, look at the Python example: it's the exact same implementation I translated into PHP syntax above. So my terse implementation is an exact match for the Python example and it's a functional match for the Ruby example. Hence, I can't help but think that PHP and Perl were misrepresented by making them jump through unnecessary hoops that do nothing but make the language look more complicated.
class Int(object):
def __init__(self, value):
self.value = value
@property
def value(self):
print("Accessing value")
return self.value
@value.setter
def value(self, value):
print("Setting value")
self.value = value