【发布时间】:2021-02-18 21:35:17
【问题描述】:
在 EVAL 中绑定哈希时遇到了一些我不理解的问题。在 EVAL 之外绑定散列按预期工作。 EVAL 中的未绑定哈希按预期工作。但是在 EVAL 中绑定散列并不像我预期的那样工作。 (我的期望可能是错误的。)这是代码:
这行得通:
#!/usr/bin/env raku
class Hash::Test does Associative {
has %.hash;
multi method STORE(@pairs) {
for @pairs -> $pair {
self.STORE: $pair
}
}
multi method STORE(Pair $pair) {
%!hash{$pair.key} = $pair.value;
}
}
no strict;
%hash-test := Hash::Test.new;
%hash-test = foo => 'bar', baz => 'quux';
say %hash-test;
输出:
$ ./hash-binding-works.raku
Hash::Test.new(hash => {:baz("quux"), :foo("bar")})
这行得通:
#!/usr/bin/env raku
class Foo {
use MONKEY-SEE-NO-EVAL;
method eval(Str $code) {
EVAL $code;
}
}
my $code = q:to/END/;
no strict;
%hash = foo => 'bar', baz => 'quux';
END
Foo.eval: $code;
say %Foo::hash;
输出:
$ ./hash-EVAL-works.raku
{baz => quux, foo => bar}
但这不起作用:
#!/usr/bin/env raku
class Hash::Test does Associative {
has %.hash;
multi method STORE(@pairs) {
for @pairs -> $pair {
self.STORE: $pair
}
}
multi method STORE(Pair $pair) {
%!hash{$pair.key} = $pair.value;
}
}
class Foo {
use MONKEY-SEE-NO-EVAL;
method eval(Str $code) {
EVAL $code;
}
}
my $code = q:to/END/;
no strict;
%hash-test := Hash::Test.new;
%hash-test = foo => 'bar', baz => 'quux';
say %hash-test;
END
no strict;
Foo.eval: $code;
say %Foo::hash-test;
输出:
$ ./hash-EVAL-does-not-work.raku
Hash::Test.new(hash => {:baz("quux"), :foo("bar")})
{}
Hash::Test 不是我真正使用的类,而是我打高尔夫球的目的。谁能解释这里发生了什么?谢谢!
【问题讨论】:
-
你为什么使用
no strict?如果删除它会发生什么? -
@ElizabethMattijsen 对我来说,如果我运行最后一个代码但没有
no strict;,我会得到“未声明变量 '%hash-test'”。 -
@raiph,感谢您的关注。是的,那是复制/粘贴失败。我已经更正了。
-
@ElizabethMattijsen,@raiph 说的是正确的。我使用它来与最后一个不起作用的代码块保持一致。由于 EVAL 无法在周围范围内创建词法,因此我无法使用
my。
标签: class hash binding eval raku