raku

Elegant way to write when inside a for loop?


I can write something like this (elem here is an XML::Element but it doesn't really matter):

for $elem.nodes {
    when XML::Element { ... }
    when XML::Text { ... }
    ...
    default { note qq{Ignoring unknown XML node "$_".} }
}

which looks nice, but doesn't give me a readable name for $_ inside the code using it, which is why I'd prefer to write this:

for $elem.nodes -> $child {
    when XML::Element { ... }
    when XML::Text { ... }
    ...
    default { note qq{Ignoring unknown XML node "$child".} }
}

but this doesn't work because now $_ isn't set, and so I actually need to write

for $elem.nodes -> $child {
    given $child {
        when XML::Element { ... }
        when XML::Text { ... }
        ...
        default { note qq{Ignoring unknown XML node "$child".} }
    }
}

which is a bit redundant and adds an extra level of indentation.

It's definitely not the end of the world, but am I missing some simple way to have both a readable variable name and avoid given?


Solution

  • You can bind the variable above the when statements, it's a little uglier but it does the job.

    for $elem.nodes {
        my $child = $_;
        when XML::Element { say 'I am XML!' }
        when XML::Text { say 'I am text!' }
        default { say "I am default: $child" }
    }
    

    Edit: In Raku I think it is perfectly reasonable to stick to using $_ seeing as the idea of $_ has been around for quite some time.