On Wed, Mar 18, 2015 at 11:32 AM, Tom Browder <tom.brow...@gmail.com> wrote:
> On Wed, Mar 18, 2015 at 7:22 AM, Moritz Lenz <mor...@faui2k3.org> wrote:
> ...
>> http://doc.perl6.org/language/objects#Object_Construction lists at least two
>> possible ways. Probably the most interesting one is BUILDALL with a
>> callsame; see the last example (or example skeleton) in that section.

For my purposes I think the BUILD is best.  The BUILDALL method seems
to put me in limbo as far as the constructed object and using self.

I made a simple class and a driver Perl script:

$ cat T.pm <<HERE_PM
class T;

has $.a is rw;
has $.b is rw;
has $.c is rw;

submethod BUILD(
# set defaults here
:$!a = 15,
:$!b,
:$!c,
      ) {
  self.set_b;
}

multi method set_b {
  if (self.a < 10) {
    self.b = 1;
  }
  else {
    self.b = 0;
  }
}

multi method set_b($x) {
  self.b = $x;
}
HERE_PM

$ cat T.pl <<HERE_PL
#!/usr/bin/env perl6

use v6;
use lib '.';
use T;
my $t = T.new;
say "\$t.a = {$t.a}";
say "\$t.b = {$t.b}";
say "\$t.c = {$t.c.defined ?? $t.c !! 'undefined'}";
$t.set_b(20);
$t.c = 'defined';
say "\$t.a = {$t.a}";
say "\$t.b = {$t.b}";
say "\$t.c = {$t.c.defined ?? $t.c !! 'undefined'}";
HERE_PM

$ perl6 T.pl
$t.a = 15
$t.b = 0
$t.c = undefined
$t.a = 15
$t.b = 20
$t.c = defined

Best,

-Tom

Reply via email to