Perl嵌套哈希哈希

前端之家收集整理的这篇文章主要介绍了Perl嵌套哈希哈希前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在根据文本输入确定如何在perl中创建嵌套哈希时遇到了一些麻烦.

我需要这样的东西

my % hash = {
key1 => \%inner-hash,key2 => \%inner-hash2
}

然而我的问题是我不知道apriori会有多少内部哈希.为此,我编写了以下片段来测试是否可以在循环中创建str变量,并将其引用存储在数组中,然后再解除引用.

{
    if($line =~ m/^Limit\s+$mc_lim\s+$date_time_lim\s+$float_val\s+$mc\s+$middle_junk\s+$limit  \s+$value/) {
        my $str = $1 . ' ' . $2 . ' ' . $7;
        push (@test_array_reference,\$str);
     }
}
foreach (@test_array_reference) {  
    say $$_;
}

Perl死于标量运行时错误.我在这里有点失落.任何帮助将不胜感激.

解决方法

要回答您的第一个(主要?)问题,如果您浏览文本并随时创建它们,则无需知道要创建多少哈希值.此示例使用以空格分隔的字符串的单词作为键,但您可以使用任何输入文本作为您的用途.

my $text = 'these are just a bunch of words';
my %hash;

my $hashRef = \%hash;           # create reference to initial hash
foreach (split('\s',$text)){
    $hashRef->{$_} = {};        # create anonymous hash for current word
    $hashRef = $hashRef->{$_};  # walk through hash of hashes
}

您还可以引用任意内部哈希并设置值,

$hash{these}{are}{just}{a}{bunch}{of}{words} = 88;
$hash{these}{are}{just}{a}{bunch}{of}{things} = 42;
$hash{these}{things} = 33;

要想象这一点,Data:Dumper可能有所帮助,

print Dumper %hash;

哪个生成,

$VAR1 = 'these';
$VAR2 = {
          'things' => 33,'are' => {
                     'just' => {
                                 'a' => {
                                          'bunch' => {
                                                       'of' => {
                                                                 'things' => 42,'words' => 88
                                                               }
                                                     }
                                        }
                               }
                   }
        };

猜你在找的Perl相关文章