in reply to Re^4: perl 5.38: can the body of a class declaration contain arbitrary code?
in thread perl 5.38: can the body of a class declaration contain arbitrary code?
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^6: perl 5.38: can the body of a class declaration contain arbitrary code?
by jdporter (Paladin) on Jul 05, 2023 at 22:35 UTC | |
by cavac (Prior) on Jul 07, 2023 at 09:34 UTC |