"In other words, can 'instance variables' be defined outside a constructor?"
They can using mop, a module which is planned for inclusion in a future version of Perl (perhaps 5.22 or 5.24), though there's a trial version on CPAN already.
The syntax differs from normal Perl variables, in that instance variables are declared with has instead of my, and instead of having a $ sigil (like $foo) they have a $! twigil (like $!foo).
For example:
use v5.16; use mop; use warnings; class Example { has $!name; has $!score; method getName () { return $!name; } method getScore () { return $!score; } } my $eg = Example->new(name => "Bob", score => 9.9); say $eg->getName; say $eg->getScore;
The mop module is inspired by the already-existing, and more stable Moose framework. Here's how you'd accomplish the same thing in Moose:
use v5.14; use warnings; package Example { use Moose; has name => (is => 'ro', reader => 'getName'); has score => (is => 'ro', reader => 'getScore'); } my $eg = Example->new(name => "Bob", score => 9.9); say $eg->getName; say $eg->getScore;
Or you could use Moo:
use v5.14; use warnings; package Example { use Moo; has name => (is => 'ro', reader => 'getName'); has score => (is => 'ro', reader => 'getScore'); } my $eg = Example->new(name => "Bob", score => 9.9); say $eg->getName; say $eg->getScore;
Or Moops:
use Moops; class Example :ro { has name => (reader => 'getName'); has score => (reader => 'getScore'); } my $eg = Example->new(name => "Bob", score => 9.9); say $eg->getName; say $eg->getScore;
In reply to Re: Object oriented Perl and Java: A brief examination of design.
by tobyink
in thread Object oriented Perl and Java: A brief examination of design.
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |