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

时间:2014-10-22 21:46:05

标签: perl recursion tree pass-by-reference

我目前正在尝试使用Perl实现后缀树,但是,当我尝试设置树函数的引用时,未设置引用位置,如果我通过字符串传递地址然后检查文本中的文本字符串vs哈希表的位置,它们是不同的。任何帮助表示赞赏!

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);

2 个答案:

答案 0 :(得分:4)

您需要括号来消除歧义。这样:

\%treeRoot, $count = @_;

意味着:

\%treeRoot; 
$count = @_;

因为赋值运算符=的值高于逗号运算符, precedence。运行该代码时收到的警告告诉您:Useless use of reference constructor in void context

要正确传递参数,您需要括号:

(\%treeRoot, $count) = @_;

不幸的是,这不起作用,因为你无法以这种方式分配引用。以下错误告诉您:Can't modify reference constructor in list assignment

所以你需要的是将引用传递给标量:

my ($href, $count) = @_;
print $href->{'value'};

我认为这种方法有点倒退。通过引用传递变量可能会成为错误的来源。更自然的解决方案是使用子例程的返回值来赋值:

sub foo {
    my %hash;
    $hash{'value'} = ....
    ....
    return \%hash;
}

my $hashref = foo();
print $hashref->{'value'};

答案 1 :(得分:0)

您的问题实际上并不是如何传递哈希引用,而是如何接收哈希引用,因为以下内容不起作用:

\%treeRoot, $count = @_;

基本上,您需要将引用分配给标量,如下所示:

use strict;
use warnings;

sub example_sub {
    my ($hashref, $count) = @_;

    # Add two values to the hash:
    $hashref->{newkey} = 'val';
    $hashref->{newkey2} = 'val2';
}

my %root;

example_sub(\%root, 2);

use Data::Dump;
dd \%root;

输出:

{ newkey => "val", newkey2 => "val2" }

如果您不想修改原始哈希,可以将值分配给子中的新哈希:

my %newhash = %$hashref;

有关使用参考文献的更多信息,请查看:perlref - Perl references and nested data structures