我在使用 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
?如果将其移除会发生什么? - Elizabeth Mattijsenno strict;
,我会得到“变量'%hash-test'未声明”。@ElizabethMattijsen - raiphmy
。 - JustThisGuy