我想創建一個子程序,將元素(帶有值的鍵)添加到先前定義的散列中。這個子程序在一個循環中被調用,所以哈希增長。我不希望返回的哈希覆蓋現有的元素。如何返回一個數組和一個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.
哪裏是我的錯?
我很感激任何意見。
一個單獨的問題哇感謝這工作得很好:) –