在Perl中动态/递归地构建哈希?

Gau*_*nia 8 recursion perl hash perl-data-structures

我是Perl的新手,我正试图递归地构建一个哈希并且无处可去.我尝试搜索动态构建哈希的教程,但我能找到的只是关于哈希的介绍性文章.如果你指出我正确的方向或建议一篇好文章/教程,我将不胜感激.

我试图从一个文件中读取具有路径的文件

one/two/three
four
five/six/seven/eight
Run Code Online (Sandbox Code Playgroud)

我想建立像哈希一样的哈希

VAR = {
    one : {
        two : {
            three : ""
        }
    }
    four : ""
    five : {
        six : {
            seven : {
                 eight : ""
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我目前使用的脚本是:

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);
}
Run Code Online (Sandbox Code Playgroud)

yst*_*sth 7

Data::Diver 很好地覆盖了这个利基,人们不应该重新发明轮子.

use strict;
use warnings;
use Data::Diver 'DiveVal';
use Data::Dumper;

my $root = {};
while ( my $line = <DATA> ) {
    chomp($line);
    DiveVal( $root, split m!/!, $line ) = '';
}
print Dumper $root;
__DATA__
one/two/three
four
five/six/seven/eight
Run Code Online (Sandbox Code Playgroud)


JB.*_*JB. 6

这有点牵强,但它有效:

sub insert {
  my ($ref, $head, @tail) = @_;
  if ( @tail ) { insert( \%{$ref->{$head}}, @tail ) }
  else         {            $ref->{$head} = ''      }
}

my %hash;
chomp and insert \%hash, split( '/', $_ ) while <>;
Run Code Online (Sandbox Code Playgroud)

它依赖于autovivification,这对于初学者来说无疑是有点先进的.

什么可能使你的问题的任何答案有点扭曲,你要求叶子中的空字符串,这是与节点的哈希值不同的"类型",并且需要不同的解除引用操作.

  • 只需将`while`循环和`chomp`显式放在自己的行上,对于beginner_来说它将是可读的_. (3认同)