Moritz Lenz |Perl 6| wrote:
Paul Fenwick <pjf <at>> writes:

for ($foo) {
        when ($_ < 500)  { ++$_ }
        when ($_ > 1000) { --$_ }
        default          { say "Just right $_" }
Ahh... that's exactly what I was looking for.  Thanks.

Makes you wonder why the 'given' keyword was added, when for/when is so close...

I'd assume 'given' provides scalar context onto its argument, 'for'
obviously provides list context.

But I guess the main difference is that 'for' is associated with
iteration, and IMHO it feels unnatural to iterate over one item.

"given" and "when" are not dedicated as a matched set as in select/case or such in other languages. They are independent features. 'given' sets a topic if you just need to do that. If you are in a loop or otherwise like to use the $_ variable, you don't need to. If you lean away from using the default variable and like to name things, then 'given' comes in handy for 'when' and for something like Pascal's 'with' statement for accessing a bunch of methods in one object.

'for' takes a list as its argument. The parens don't add anything, they are just for old times' sake. The writeup in S04 is not detailed, but if the control argument is equivalent to *$@, then you specified a list of one item.
But the resulting $_ is a single item.


Reply via email to