我目前正在尝试使用 Perl 实现后缀树,但是,当我尝试设置树函数的引用时,未设置引用位置,如果我通过字符串传递地址,然后检查中的文本字符串与哈希表的位置,它们是不同的。如有任何帮助,我们将不胜感激!
use strict;
use warnings;
use Data::Dumper;
my $count = 0;
my $str; # holds the complete string
my %root;
# takes in all lines of code
open(IN, '<:encoding(UTF-8)', $ARGV[0]) or die "Could not open file '$ARGV[0]' $!\n";
while (<IN>) {
chomp;
# concatinates with string
$str .= $_;
}
# closes input
close(IN);
#length of input string
my $l_size = length($str) - 1;
#recursively makes
sub tree {
#recursive root
my %treeRoot;
#checking incomming data
print "1 ".Dumper(\@_)."\n";
#checking incomming data
print "2 ".Dumper(\%root)."\n";
#attempts to set tree's refrence
\%treeRoot, $count = @_;
#checking incomming data
print "3 ".Dumper(\%root)."\n";
#checking incomming data
print "4 ".$count."\n";
#leaf for each node
my %leaf;
for (my $i = 0; $i < $l_size; $i++) {
#creates alphabet tree
$treeRoot { substr($str, $i, 1) } = %leaf;
}
#checking incomming data
print "5 ".Dumper(\%root)."\n";
while ($count > 0) {
#checking incomming data
print "loop 6 ".Dumper(\%root)."\n";
$count--;
#checking incomming data
print "loop 7 ".$count."\n";
#recursion not implamented yet
#tree(\$treeRoot{'a'}, $count);
}
}
tree(\%root, 2);
#print Dumper(\%root);
最佳答案
您需要括号来消除歧义。这:
\%treeRoot, $count = @_;
的意思是:
\%treeRoot;
$count = @_;
因为赋值运算符=
具有更高的precedence比逗号运算符 ,
更重要。运行该代码时收到的警告告诉您:在 void 上下文中无用地使用引用构造函数
。
要正确传递参数,您需要括号:
(\%treeRoot, $count) = @_;
不幸的是,这不起作用,因为您无法以这种方式分配给引用。以下错误告诉您:无法修改列表赋值中的引用构造函数
。
所以您需要的是将引用传递给标量:
my ($href, $count) = @_;
print $href->{'value'};
不过,我认为这种方法有点落后。通过引用传递变量可能会成为错误的根源。更自然的解决方案是使用子例程的返回值来赋值:
sub foo {
my %hash;
$hash{'value'} = ....
....
return \%hash;
}
my $hashref = foo();
print $hashref->{'value'};
关于perl - 如何通过 Perl 引用传递哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26517687/