2013-07-06 11 views
1

我想創建一個子程序,將元素(帶有值的鍵)添加到先前定義的散列中。這個子程序在一個循環中被調用,所以哈希增長。我不希望返回的哈希覆蓋現有的元素。如何返回一個數組和一個hashref?

最後,我想輸出整個累計散列。

現在它不打印任何東西。最後的散列看起來是空的,但不應該是這樣。 我試過用哈希引用,但它並沒有真正的工作。在很短的形式,我的代碼如下:

sub main{ 
    my %hash; 
    %hash=("hello"=>1); # entry for testing 

    my $counter=0; 
    while($counter>5){ 
    my(@var, $hash)=analyse($one, $two, \%hash); 
    print ref($hash); 

    # try to dereference the returning hash reference, 
    # but the error msg says: its not an reference ... 
    # in my file this is line 82 
    %hash=%{$hash}; 

    $counter++; 
    } 

    # here trying to print the final hash 
    print "hash:", map { "$_ => $hash{$_}\n" } keys %hash; 
} 

sub analyse{ 
    my $one=shift; 
    my $two=shift; 
    my %hash=%{shift @_}; 
    my @array; # gets filled some where here and will be returned later 

    # adding elements to %hash here as in 
    $hash{"j"} = 2; #used for testing if it works 

    # test here whether the key already exists or 
    # otherwise add it to the hash 

    return (@array, \%hash); 
} 

但是這並不在所有的工作:子程序analyse接收的哈希值,但其返回散列引用是空的,或者我不知道。最後什麼都沒有打印。

首先,它說,它不是一個參考,現在它說:

Can't use an undefined value as a HASH reference 
    at C:/Users/workspace/Perl_projekt/Extractor.pm line 82.

哪裏是我的錯?

我很感激任何意見。

回答

5

數組在perl中變得平坦,所以你的hashref被篡改爲@var

嘗試這樣:

my ($array_ref, $hash_ref) = analyze(...) 

sub analyze { 
    ... 
    return (\@array, \@hash); 
} 
+0

一個單獨的問題哇感謝這工作得很好:) –

0

如果按引用傳遞的哈希(如你在做),你不必返回它作爲子程序的返回值。您在子程序中對散列的操縱將會持續。

my %h = (test0 => 0); 

foreach my $i (1..5) { 
    do_something($i, \%h); 
} 

print "$k = $v\n" while (my ($k,$v) = each %h); 


sub do_something { 
    my $num = shift; 
    my $hash = shift; 

    $hash->{"test${num}"} = $num; # note the use of the -> deference operator 
} 

您使用子程序內@array的需要:-)