2015-07-04 52 views
0

我在同一個哈希的子程序外部和內部創建鍵。但是,在子例程之後,調用子例程之前創建的鍵中的值現在被解釋爲數組引用。哈希鍵值在perl中的子程序後更改爲數組引用

#!/usr/bin/perl 
use module; 
use strict; 
use warnings; 
my %hash; 
my $count = 0; 

my @array = ("a", "b", "c", "d"); 

for my $letter (@array) { 
    $hash{$letter} = $count; 
    $count++; 
} 

# need "\" to pass in hash otherwise changes 
# will get lost outside of subroutine 
foreach my $x (sort keys %hash) { 
    print "first $hash{$x}\n"; 
} 

module::add_ten(\%hash); 

foreach my $p (sort keys %hash) { 
    # $hash{$p} is printing array references, but before it was 
    # printing the value I desired. What did the subroutine do? 
    print "second $hash{$p} $hash{$p}->{ten}\n"; 
} 

,這裏是與子程序

package module; 

sub add_ten { 
my $count = 10; 
    # this passes the full array as reference 
    my ($hash_ref) = @_; # $hash_ref is actually %hash (yes, the % is not a typo) 
    my @keys = keys $hash_ref; 
    foreach my $ltr (sort keys $hash_ref) { 
     $hash_ref->{$ltr} = { ten => $count }; 
     $count++; 
    } 
} 
1; 

這裏的模塊輸出:

first 0 
first 1 
first 2 
first 3 
second HASH(0x7ff0c3049c50) 10 
second HASH(0x7ff0c3049bc0) 11 
second HASH(0x7ff0c3049b90) 12 
second HASH(0x7ff0c3049b60) 13 

我期待的輸出爲:

first 0 
first 1 
first 2 
first 3 
second 0 10 
second 1 11 
second 2 12 
second 3 13 

我修改了我的模塊:

package module; 

sub add_ten { 
    my $count = 10; 
    # this passes the full array as reference 
    my ($hash_ref) = @_; # $hash_ref is actually %hash (yes, the % is not a typo) 
    my @keys = keys $hash_ref; 
    foreach my $ltr (sort keys $hash_ref) { 
     $hash_ref->{$ltr}{ten}=$count; 
     $count++; 
    } 
} 
1; 

和主腳本(註釋掉使用嚴格,以得到它的工作需要):

#!/usr/bin/perl 
use module; 
#use strict; 
use warnings; 
my %hash; 
my $count = 0; 

my @array = ("a", "b", "c", "d"); 

for my $letter (@array) { 
    $hash{$letter} = $count; 
    $count++; 
} 

# need "\" to pass in hash otherwise changes 
# will get lost outside of subroutine 
foreach my $x (sort keys %hash) { 
    print "first $hash{$x}\n"; 
} 

module::add_ten(\%hash); 

foreach my $p (sort keys %hash) { 
    print "second $hash{$p} $hash{$p}{ten}\n"; 
} 

,但是這是我試圖去。

+0

這番話應該讀'%$ hash_ref是%hash' – ikegami

+1

'使用module'應該是'使用Module',模塊本身應該是'Module.pm'和遏制一個package語句'package Module' – Borodin

回答

5

$hash_ref%hash參考,所以,當你改變哈希通過$hash_ref引用的元素的值,你就改變了哈希%hash的值。

這意味着,當你做

$hash_ref->{$ltr} = { ten => $count }; 

你正在做

$hash{a} = { ten => 10 }; 

它應該是毫不奇怪,$hash{a}不再包含零。你將不得不改變你的數據結構。您可以使用下列內容:

$hash{a}{value} = 0; 
$hash{a}{subhash}{ten} = 10; 
+0

我想$ hash {a} = 0和$ hash {a} {ten} = 10。但是$ hash {a}在子例程後面返回一個哈希引用(我不想) ,在子程序$ hash {a}返回「0」之前 – happytuna

+3

您正在執行'$ hash {a} = 0; $ hash {a} = \%subhash;',並詢問爲什麼'$ hash {a}'不是零。它一次只能保存這兩個值中的一個。 – ikegami

+0

爲我的答案增加了一個解決方案。 – ikegami