Trey Harris writes:
> Can anyone explain the rules of placeholder attachment? i.e., in the
> example in Perl6::Placeholder's manpage,
>
> grep { $data{$^value} } 1..10;
>
> C<$^value> is clearly intended to attach to the outer closure C<{
> $data{$^value} }>, not the inner closure C<{$^value}>. But how does the
> compiler know? What is the general rule?
This is a tough question, one to which I don't know the answer. I'll
do something different for a change and speculate :-)
In your first example, it does what you mean because the hash subscript
isn't a closure. Curlies are always closures, except when they're not
(to be specific, in hash subscripts and hash constructors).
> It's easy to just say "don't nest placeholder-using closures," but that
> doesn't seem workable in practice since every block is a closure, unless
> placeholders are forbidden from all but the most trivial cases. Absurdly
> trivial, it seems. How about
>
> $sub = { if $^a { $^b = $^a } };
I want this to work. It could look at C<if>'s signature and see that
the closure it is expecting wants arguments, and since it doesn't, it
knows that they belong outside. But that doesn't generalize.
I think a better solution would be to associate all placeholders with
the outermost closure that introduced a placeholder. For example:
$sub = { { $^a + $^b } };
Would bind them both to the inner one, while:
$sub = { $^a; { $^a + $^b } };
Would bind them both to the outer one. Since placeholders are meant for
small scopes, this seems a good heuristic. That second example was
obviously a hack to get it to work right. The clean way to do that
would be:
$sub = -> $a, $b { { $a + $b } };
Luke