2013-11-14 75 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

明白了:)谢谢。 –