默认情况下,哈希将所有键转换为字符串.当您的密钥是可能接近的数字时,这会导致问题:
> my %h; %h{1/3} = 1; %h{0.333333} = 2; dd %h;
Hash %h = {"0.333333" => 2}
Run Code Online (Sandbox Code Playgroud)
当然,这可以修复如下:
> my %h{Real}; %h{1/3} = 1; %h{0.333333} = 2; dd %h;
Hash[Any,Real] %h = (my Any %{Real} = 0.333333 => 2, <1/3> => 1)
Run Code Online (Sandbox Code Playgroud)
但现在我需要哈希数字哈希,例如{ 1/3 => { 2/3 => 1, 0.666667 => 2 } }
.
> my %h{Real}; %h{1/3}{2/3} = 1; %h{1/3}{0.666667} = 2; dd %h;
Hash[Any,Real] %h = (my Any %{Real} = <1/3> => ${"0.666667" => 2})
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
我能搞清楚的是以下解决方法:
> my %h{Real}; %h{1/3} //= my %{Real}; %h{1/3}{2/3} = 1; %h{1/3}{0.666667} = 2; dd %h;
Hash[Any,Real] %h = (my Any %{Real} = <1/3> => $(my Any %{Real} = <2/3> => 1, 0.666667 => 2))
Run Code Online (Sandbox Code Playgroud)
但这只是烦人的.
Bra*_*ert 13
以下作品:
my Hash[Real,Real] %h{Real};
%h{1/3} .= new;
%h{1/3}{2/3} = 1;
Run Code Online (Sandbox Code Playgroud)
这不是很好.
以下也适用于解决方法.
my Hash[Real,Real] %h{Real};
%h does role {
method AT-KEY (|) is raw {
my \result = callsame;
result .= new unless defined result;
result
}
}
%h{1/3}{2/3} = 1;
say %h{1/3}{2/3}; # 1
Run Code Online (Sandbox Code Playgroud)
如果您有多个这样的变量:
role Auto-Instantiate {
method AT-KEY (|) is raw {
my \result = callsame;
result .= new unless defined result;
result
}
}
my Hash[Real,Real] %h{Real} does Auto-Instantiate;
Run Code Online (Sandbox Code Playgroud)