2014-10-22 5 views
2

현재 Perl을 사용하여 접미어 트리를 구현하려고하지만 트리 함수에 대한 참조를 설정하려고 할 때 참조 위치가 설정되지 않은 경우 주소를 전달하면 문자열을 통해 문자열의 텍스트와 해시 테이블의 위치를 ​​비교하면 서로 다릅니다. 어떤 도움을 주셔서 감사합니다!Refrence로 해시 테이블을 전달하는 방법 Perl

\%treeRoot, $count = @_; 

는 기본적으로, 당신은 당신의 참조를 할당해야합니다 :

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

답변

4

모호성을 제거하려면 괄호가 필요합니다. 이 :

\%treeRoot, $count = @_; 

이 의미 할당 연산자 =는 콤마 연산자 ,보다 높은 precedence 갖는다

\%treeRoot; 
$count = @_; 

때문에. 해당 코드를 실행하여 얻은 경고는 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'}; 
+0

완벽하게 작동했습니다. 정말 고맙습니다! –

+0

@anon 당신을 진심으로 환영합니다. – TLP

0

귀하의 질문은 다음이 작동하지 않습니다 같은 해시 참조를 전달하는,하지만 어떻게 그것을받는 방법을 실제로하지 않습니다 스칼라과 같이 :

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