在 Perl 中动态/递归构建哈希?
我对 Perl 很陌生,我正在尝试递归地构建哈希,但一无所获。我尝试搜索动态构建哈希的教程,但我能找到的只是有关哈希的介绍性文章。如果您为我指出正确的方向或建议一篇不错的文章/教程,我将不胜感激。
我正在尝试从具有以下形式路径的文件中读取内容
one/two/three
four
five/six/seven/eight
,并且我想构建一个像
VAR = {
one : {
two : {
three : ""
}
}
four : ""
five : {
six : {
seven : {
eight : ""
}
}
}
}
我当前使用的脚本一样的哈希:
my $finalhash = {};
my @input = <>;
sub constructHash {
my ($hashrf, $line) = @_;
@elements = split(/\//, $line);
if(@elements > 1) {
$hashrf->{shift @elements} = constructHash($hashrf->{$elements[0]}, @elements );
} else {
$hashrf->{shift @elements} = "";
}
return $hashrf;
}
foreach $lines (@input) {
$finalhash = constructHash($finalhash, $lines);
}
I'm quite new to Perl and I'm trying to build a hash recursively and getting nowhere. I tried searching for tutorials to dynamically build hashes, but all I could find were introductory articles about hashes. I would be grateful if you point me towards the right direction or suggest a nice article/tutorial.
I'm trying to read from a file which has paths in the form of
one/two/three
four
five/six/seven/eight
and I want to build a hash like
VAR = {
one : {
two : {
three : ""
}
}
four : ""
five : {
six : {
seven : {
eight : ""
}
}
}
}
The script I'm using currently is :
my $finalhash = {};
my @input = <>;
sub constructHash {
my ($hashrf, $line) = @_;
@elements = split(/\//, $line);
if(@elements > 1) {
$hashrf->{shift @elements} = constructHash($hashrf->{$elements[0]}, @elements );
} else {
$hashrf->{shift @elements} = "";
}
return $hashrf;
}
foreach $lines (@input) {
$finalhash = constructHash($finalhash, $lines);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我从来没有做过这样的事情,所以这种方法可能是错误的,但是好吧,这是我的镜头:
编辑:已修复!
EDIT2:(我认为)尾调用优化版本,因为!
I've never done something like this, so this approach is likely to be wrong, but well, here's my shot:
EDIT: Fixed!
EDIT2: A (I think) tail-call optimized version, because!
我运行了您的代码并发现了一些问题:
@elements
的范围。constructHash()
的第二个参数是一个字符串,但在内部的递归调用中,您传递一个@elements
数组,试试这个。
它会产生
记住,Perl 哈希值是没有排序的。
I ran your code and found a few problems:
@elements
properly.constructHash()
is a string, but on the recursive call inside, you pass an array of@elements
Try this.
It produces
Remember, Perl hashes aren't ordered.
基础知识:
The basics:
Data::Diver
很好地涵盖了这个利基市场,人们不应该重新发明轮子。Data::Diver
covers this niche so well that people shouldn't reinvent the wheel.这有点牵强,但它确实有效:
它依赖于自动生存,这对于初学者来说确实有点高级。
可能会使您的问题的答案有点扭曲的是,您要求叶子中的空字符串,它的“类型”与节点的哈希值不同,并且需要不同的取消引用操作。
This is a bit far-fetched, but it works:
It relies on autovivification, which is admittedly a bit advanced for a beginner.
What would probably make any answer to your question a bit twisted is that you ask for empty strings in the leaves, which is of a different "type" than the hashes of the nodes, and requires a different dereferencing operation.