perl - 如何通过 Perl 引用传递哈希表

标签 perl recursion tree pass-by-reference

我目前正在尝试使用 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/

相关文章:

perl - 有没有什么地方可以找到关于 Perl 模块相对流行度的信息?

perl - 如何将找不到的 Mojolicious Lite 默认错误更改为自定义 json 响应

c - perl 中是否有与 read() 相反的函数,就像 C 中的 fwrite() 一样?

正则表达式搜索并替换为 Perl 中的变量

python - 封闭式斐波那契数列

java - Java中的递归动态规划背包解决方案

java - 如何在 Boggle 游戏板中递归搜索单词?

ubuntu - 使用终端确定具有子树的树的总大小(以 Kb 为单位)

algorithm - 如何检查给定的生成树是否为 MST?

c++ - 状态机实现