从一个简单的数组中递归构建嵌套哈希
得到了这个:
my @list = <one two three>;
my %hash;
my $item1 = @list.shift;
%hash{$item1} = {$item1 => 1};
my $item2 = @list.shift;
%hash{$item1} = {$item2 => 1};
my $item3 = @list.shift;
%hash{$item1}{$item2} = {$item3 => 1};
say %hash;
输出此期望的数据结构:
{one => {two => {three => 1}}}
显然,如果递归是递归的话,这会更好,所以我写了此:
sub get-hash(%parent-hash, $last-item, *@list) {
my $item = @list.shift;
%parent-hash{$last-item} = { $item => 1 };
get-hash(%parent-hash{$last-item}, $item, @list) if @list;
return %parent-hash<root>;
}
%hash = get-hash({}, 'root', @list2);
输出:
{one => {two => {three => 1}}}
虽然有效,但它感觉很不高,尤其是必须传递root
参数到潜艇,然后将其删除。有什么建议吗?
Got this:
my @list = <one two three>;
my %hash;
my $item1 = @list.shift;
%hash{$item1} = {$item1 => 1};
my $item2 = @list.shift;
%hash{$item1} = {$item2 => 1};
my $item3 = @list.shift;
%hash{$item1}{$item2} = {$item3 => 1};
say %hash;
Outputs this desired data structure:
{one => {two => {three => 1}}}
Obviously, this would be better if it were recursive, so I wrote this:
sub get-hash(%parent-hash, $last-item, *@list) {
my $item = @list.shift;
%parent-hash{$last-item} = { $item => 1 };
get-hash(%parent-hash{$last-item}, $item, @list) if @list;
return %parent-hash<root>;
}
%hash = get-hash({}, 'root', @list2);
Output:
{one => {two => {three => 1}}}
Though it works, it feels inelegant, especially having to pass in a root
argument to the sub and then removing it. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在即将推出的Raku版本中,有一种整洁的方法:
||
表示您想将列表使用为多维 hash键。如果您想在当前发布的语言版本中坚持使用内容,则仍然可以直接致电操作员,因为只有语法糖丢失了:
两种情况下的输出都是您想要的:
In the upcoming Raku version, there's a neat way to do this:
The
||
indicates that you want to use the list as multi-dimensional hash keys.If you want to stick to things in the current released language versions, you can still call the operator directly, since it's only the syntax sugar that is missing:
The output in either case is as you wish:
好的,玩参数的顺序有助于简化事情:
OK, playing around with the order of the arguments helped simplify things a bit:
想要“键值”结构
您
如果
If you want ’key-value’ structure
Pair
If you really need
Hash
or