【发布时间】:2019-04-07 09:05:37
【问题描述】:
我正在尝试customized hashes。以下是尝试为类似配置的哈希实现更简单的查找:
use v6;
class X::Config::KeyNotFound is Exception {
method message() {
"Key not found!";
}
}
# A hash that allows for nested lookup using a '.' to separate keys.
# (This means that keys themselves cannot contain a dot)
# For example:
#
# %h = Config.new(%(a => %(b => 1)));
# my $foo = %h<a.b>; # <-- $foo = 1
#
class Config does Associative[Cool,Str] {
has %.hash;
multi method AT-KEY ( ::?CLASS:D: $key) {
my @keys = $key.split('.');
my $value = %!hash;
for @keys -> $key {
if $value{$key}:exists {
$value = $value{$key};
}
else {
X::Config::KeyNotFound.new.throw;
}
}
$value;
}
multi method EXISTS-KEY (::?CLASS:D: $key) {
my @keys = $key.split('.');
my $value = %!hash;
for @keys -> $key {
if $value{$key}:exists {
$value = $value{$key};
}
else {
return False;
}
}
return True;
}
multi method DELETE-KEY (::?CLASS:D: $key) {
X::Assignment::RO.new.throw;
}
multi method ASSIGN-KEY (::?CLASS:D: $key, $new) {
X::Assignment::RO.new.throw;
}
multi method BIND-KEY (::?CLASS:D: $key, $new){
X::Assignment::RO.new.throw;
}
}
my %hash = a => %(aa => 2, ab => 3), b => 4;
my %cfg := Config.new( hash => %hash );
# A dummy class to illustrate the problem:
class MyTest {
has %.config;
}
# Now this code does not work:
MyTest.new(
config => %cfg,
);
输出是:
Odd number of elements found where hash initializer expected:
Only saw: Config.new(hash => {:a(${:aa(2), :ab(3)}), :b(4)})
in block <unit> at ./p.p6 line 70
(第 70 行是MyTest.new( 行)
如果我将普通哈希传递给构造函数,则代码可以正常工作,例如使用%hash 而不是%cfg:
MyTest.new(
config => %hash,
);
【问题讨论】:
标签: raku