Con versioni più recenti di Rakudo esiste un sottoinsieme denominato UInt
che lo limita ai valori positivi.
class Wizard {
has UInt $.mana is rw;
}
In modo che non sei bloccato in un asso se avete bisogno di qualcosa di simile; Ecco come definito:
(si può lasciare fuori il my
, ma ho voluto mostrare la actual line dalla fonte Rakudo)
my subset UInt of Int where * >= 0;
si potrebbe anche fare questo:
class Wizard {
has Int $.mana is rw where * >= 0;
}
Vorrei sottolineare che il vincolo è solo un modo breve per creare un Callable.
Si potrebbe avere uno dei seguenti come where
vincolo:
... where &subroutine # a subroutine that returns a true value for positive values
... where { $_ >= 0 }
... where -> $a { $a >= 0 }
... where { $^a >= 0 }
... where $_ >= 0 # statements also work (「$_」 is set to the value it's testing)
(Se si voleva che non solo essere pari a zero si potrebbe anche usare ... where &prefix:<?>
che probabilmente è meglio scritto come ... where ?*
o ... where * !== 0
)
Se hai voglia di essere fastidioso per le persone che usano il tuo codice, potresti anche farlo.
class Wizard {
has UInt $.mana is rw where Bool.pick; # accepts changes randomly
}
Se si vuole fare in modo il valore "ha senso" quando si esaminano tutti i valori nella classe in forma aggregata, si dovrà andare a lavorare molto di più.
(Si può richiedere molta più conoscenza di attuazione, nonché)
class Wizard {
has Int $.mana; # use . instead of ! for better `.perl` representation
# overwrite the method the attribute declaration added
method mana() is rw {
Proxy.new(
FETCH => -> $ { $!mana },
STORE => -> $, Int $new {
die 'invalid mana' unless $new >= 0; # placeholder for a better error
$!mana = $new
}
)
}
}
Se si utilizza '' ne serve solo una volta. Se vuoi cambiarlo per blocco di codice usa '' proprio prima di esso. –