my $foo of Num where { 0 <= $^n < 10 };
Is the following also valid?
my $foo where { 0 <= $^n < 10 };
Or does that have to be like this?
my $foo of Scalar where { 0 <= $^n < 10 };
And can $_ be used instead of $^n?
Juerd
I don't see why not. The main place C<where> will be useful is in
multimethods, and I see that as a reasonable shorthand:
multi sub foo(Bar $x, $y where { .data ~~ Bar });
> Or does that have to be like this?
>
> my $foo of Scalar where { 0 <= $^n < 10 };
>
> And can $_ be used instead of $^n?
Of course it can. You know that.
Luke
I do?
Can't say I understand well when a topic is implicitly defined and when
not. It's obvious for for-loops and given, but everything else is
blurry to me.
Juerd
Okay, I'll explain then. If you use $_ inside a closure, then it is
assumed to mean an argument to that closure. If the closure isn't given
an argument (or the block is declared to have zero arguments at compile
time) then $_ defaults to the outer lexical $_, which fixes this
problem:
for @stuff {
if something() {
print; # prints the argument to if's block
}
}
I don't think it's the cleanest solution, but it works.
Luke
Just out of curiosity, what do you think would be a cleaner solution?
And why would one not want to implement such a solution instead?
// Carl
I suppose I was a bit terse. I believe it to be a dirtier part of the
the overall clean solution we currently have. To make that cleaner
would involve making something else dirtier, such as requiring too much
information at compile time.
Ultimately, $_ should work because it's referring to an outer lexical
pad; i.e. the compiler knows that $_ belongs to some outer block.
However, because of our dynamism, that would mean all of our closures
would have to be pointy or use $^vars for parameters, which outlaws such
very nice constructs as these:
@names = map { .name } @fields;
I don't think there's anything we can do to clean it, and really we're
just sweeping that strange default behavior under the rug, and nobody
will be the wiser to what's actually going on. It looks like it knows
what you're talking about even though it really doesn't.
Luke