2013-11-14 104 views
1

我將線索的哈希引用存儲到共享的@stories變量,然後無法訪問它們。無法從hashref獲取哈希值

my @stories : shared=(); 

    sub blah { 
    my %stories : shared=(); 
    <some code> 
     if ($type=~/comment/) { 
      $stories{"$id"}="$text"; 
      $stories{"$id"}{type}="$type"; 
      lock @stories; 
      push @stories, \%stories; 
     } 
    } 

# @stories is a list of hash references which are shared from the threads;

   foreach my $story (@stories) { 
       my %st=%{$story}; 
       print keys %st;  # <- printed "8462529653954" 
       print Dumper %st;  # <- OK 
       my $st_id = keys %st; 
       print $st_id;   # <- printed "1" 
       print $st{$st_id};  # <- printed "1/8" 
      } 

print keys %st works as expected but when i set in to a variable and print, it returns "1".

Could you please advice what I'm doing wrong. Thanks in advance.

+2

你期望發生的? '$ st_id = keys%st'與'$ st_id = scalar(keys%st)'相同,意思是將'$ st_id'設置爲散列'%st'中的鍵數。 – mob

+0

我希望$ st_id將是一個關鍵。即8462529653954. –

+0

您是否知道「my%st =%{$ story}」正在製作哈希的副本?對'%st'所做的任何更改都不會反映在原始哈希引用中。 – cjm

回答

3

In scalar context, keys %st返回哈希%st元件的數量。

%st = ("8462529653954" => "foo"); 
$st_id = keys %st; 

print keys %st;    # "8462529653954" 
print scalar(keys %st);  # "1" 
print $st_id;    # "1" 

要提取單個鍵呼出的%st,在列表上下文中進行從keys %st分配。

my ($st_id) = keys %st;  # like @x=keys %st; $st_id=$x[0] 
print $st_id;    # "8462529653954" 
+0

這是行得通的,謝謝。 但實際上我不明白爲什麼鍵%st是一個列表? –

+0

@TigranKhachikyan,因爲散列通常有多個鍵。 – cjm

+0

明白了:)謝謝。 –