动态/递归地在Perl中构建哈希? [英] Dynamically/recursively building hashes in Perl?
问题描述
我对Perl很陌生,我试图递归地构建一个散列并且无处可去。我试图寻找教程来动态构建哈希,但我能找到的只是关于哈希的介绍性文章。如果您将我指向正确的方向或者提出一篇不错的文章/教程,我将不胜感激。
我试图从一个文件中读取
一/二/三
四
五/六/七/八
,我想构建一个像
VAR = {
one:{
二:{
三:
}
}
四:
五:{
六:{
七: {
8:
}
}
}
}
我目前使用的脚本是:
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} =;
}
返回$ hashrf;
foreach $ lines(@input){
$ finalhash = constructHash($ finalhash,$ lines);
但它可以工作:
$ p $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ @ _;
if(@tail){insert(\%{$ ref-> {$ head}},@tail)}
else {$ ref-> {$ head} =''}
}
my%hash;
chomp并插入\%hash,split('/',$ _)while<>;
它依赖于autovivification,这对于初学者来说显然有点高级。
什么可能会让你的问题有点扭曲的答案是,你问叶中的空字符串,它与节点的哈希值是不同的类型,并且需要不同的解引用操作。
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);
}
This is a bit far-fetched, but it works:
sub insert {
my ($ref, $head, @tail) = @_;
if ( @tail ) { insert( \%{$ref->{$head}}, @tail ) }
else { $ref->{$head} = '' }
}
my %hash;
chomp and insert \%hash, split( '/', $_ ) while <>;
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.
这篇关于动态/递归地在Perl中构建哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!