sub*_*ian 4 perl perl-data-structures
我在根据文本输入确定如何在perl中创建嵌套哈希时遇到了一些麻烦.
我需要这样的东西
my % hash = {
key1 => \%inner-hash,
key2 => \%inner-hash2
}
Run Code Online (Sandbox Code Playgroud)
然而我的问题是我不知道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 $$_;
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
您还可以引用任意内部哈希并设置值,
$hash{these}{are}{just}{a}{bunch}{of}{words} = 88;
$hash{these}{are}{just}{a}{bunch}{of}{things} = 42;
$hash{these}{things} = 33;
Run Code Online (Sandbox Code Playgroud)
想象一下,Data:Dumper可能有所帮助,
print Dumper %hash;
Run Code Online (Sandbox Code Playgroud)
哪个生成,
$VAR1 = 'these';
$VAR2 = {
'things' => 33,
'are' => {
'just' => {
'a' => {
'bunch' => {
'of' => {
'things' => 42,
'words' => 88
}
}
}
}
}
};
Run Code Online (Sandbox Code Playgroud)