When does for call the iterator method?

痴心易碎 提交于 2019-11-29 15:07:28

When does for call the iterator method?

As I understand, if the (single) argument to an iterating feature is a Scalar container, then it uses the value in the container and does not call .iterator. Otherwise, it calls .iterator on it, evaluating it first if it's an expression or routine call.


&logger does Forable;
.say for &logger;

This simply does not work; say is applied to &logger as a simple item.

The & is a noun marker (sigil) marking a Callable that is inherently a single thing, a single block of code.

More specifically, &logger is bound to a Scalar container whose type is Callable, exactly the same as $logger (with a $ sigil) would be if you wrote my Callable $logger:

say .WHAT, .VAR, .VAR.WHAT, .VAR.of
for my &logger, my Callable $logger

displays:

(Callable)Callable(Scalar)(Callable)
(Callable)Callable(Scalar)(Callable)

Since the type for &logger is Block+{Forable}

That's actually the type of the Callable that's contained in the Scalar container that's bound to &logger.

It's not the type of the &logger container itself, which is a Scalar, as shown above.

When given a single argument in the form of a variable, iterating features like for look at the variable, not the value contained in the variable, to see if it's Iterable. A Scalar is not Iterable.

Any idea on how to solve this?

See lizmat's answer for one approach.

I don't think you can. The basic problem is that &foo (the Callable object) and foo() (calling the Callable object) are two very different things.

Feels to me you're trying to add a method to a class, but you're working with a Sub.

You need to mixin the iterator method on the return value of logger. As I don't really understand what you're trying to achieve, it's hard to answer the question.

Looking at the result that you apparently want to achieve, I came up with this:

my %store;
multi sub logger() {
    %store
}
multi sub logger($event) {
    %store{ DateTime.new( now ) } = $event;
}

logger( "One" );
logger( "Two" );

.say for logger;

But that doesn't use roles at all. So that may not be what you're going for.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!