4 ms·
The `when` block seems to exhibit a different behavior when used as a block vs as a statement modifier. The latter lets things falls through until it matches t
by xisukar 7y ago
The `when` block seems to exhibit a different behavior when used as a block vs
as a statement modifier. The latter lets things falls through until it matches
the most general case. For instance, given
class Audience {
has $.number;
has $.gender;
has $.formality;
has $.country;
}
my @vosotros = <Spain EquitorialGuinea WesternSahara>;
my $audience = Audience.new:
:number(100), :gender('feminine'),
:formality('informal'), :country('Spain')
;
Contrast:
my $message = do given (.number, .gender, .formality, .country given $audience) {
when 1, 'masculine', 'informal', * { '¿Cómo estás mi amigo?' }
when 1, 'masculine', 'formal', * { '¿Cómo está el señor?' }
when 1, 'feminine', 'informal', * { '¿Cómo estás mi amiga?' }
when 1, 'feminine', 'formal', * { '¿Cómo está la señora?' }
when * > 1, 'feminine', 'informal', @vosotros.any { '¿Cómo estáis mis amigas?' }
when * > 1, *, 'informal', @vosotros.any { '¿Cómo estáis mis amigos?' }
when * > 1, *, * , * { '¿Cómo están ustedes?' }
}
say $message; #=> «¿Cómo estáis mis amigas?»
with this:
my $message = do given (.number, .gender, .formality, .country given $audience) {
'¿Cómo estás mi amigo?' when 1, 'masculine', 'informal', *;
'¿Cómo está el señor?' when 1, 'masculine', 'formal', *;
'¿Cómo estás mi amiga?' when 1, 'feminine', 'informal', *;
'¿Cómo está la señora?' when 1, 'feminine', 'formal', *;
'¿Cómo estáis mis amigas?' when * > 1, 'feminine', 'informal', @vosotros.any;
'¿Cómo estáis mis amigos?' when * > 1, *, 'informal', @vosotros.any;
'¿Cómo están ustedes?' when * > 1, *, * , *;
}
say $message; #=> «¿Cómo están ustedes?»
- unixhero 7y agoWhoa
- nxrabl 7y agoFortunately, the second example does throw warnings for each line of the block but the last: Useless use of constant string "¿Cómo estás mi amigo?" in sink context
- raiph 7y agoYes, that's deliberate. If you use an ordinary `when` (with its statement(s) on the right) then P6 assumes it should succeed with the value of the last statement of the matched `when`. To succeed means to leave the block and return that last value if the block's value is being kept (eg via a `do`). If you wish instead to proceed to the next statement rather than succeed, you must write `proceed`. Conversely, if you use a modifier `when` (with its statement(s) on the left) then P6 assumes it should proceed as explained above after matching. If you wish instead to succeed as explained above you must write `succeed` (with a value unless you wish to succeed with a value of `Nil`). This is great bit of language design work. Thank you Larry.