1

我将来自线程的哈希引用存储到共享的@stories 变量,然后无法访问它们。

    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"
           }

打印键 %st 按预期工作,但是当我设置一个变量并打印时,它返回“1”。

你能告诉我我做错了什么吗?提前致谢。

4

1 回答 1

3

在标量上下文中,keys %st返回 hash 中的元素数%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"
于 2013-11-14T17:51:23.773 回答