Careful, that is misleading. The field initializers run before ADJUST, regardless of the order in which they are written. This has been specified in the Corinna RFC and is how it is implemented. I don't see it specified in the docs, though, which is a bad omission and should be fixed for 5.38.1. Demo code here:
use 5.038; use feature 'class'; no warnings 'experimental'; class WithACounter { my $next_count = 1; ADJUST { say "Next count in ADJUST: $next_count"; } field $count = do { say "Next count in field init: ", $next_count; $next_count++; }; method count { $count } } say "Next count in the object: ",WithACounter->new->count;
Output:
Next count in field init: 1 Next count in ADJUST: 2 Next count in the object: 1
Given that, then it would appear that Scala-like class definition is possible; one simply has to wrap any statements other than my/field in ADJUST blocks.
This is true. Since $count = $next_count++; is an initialization with a side effect (incrementing a class variable), I would also move that into the ADJUST block. It is the only way to get it executed after other code in ADJUST.
In reply to Re^5: perl 5.38: can the body of a class declaration contain arbitrary code?
by haj
in thread perl 5.38: can the body of a class declaration contain arbitrary code?
by jdporter
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |