-3

我有一段 perl 脚本:

my $thread_count = 20

my %QUEUES;
my $current_queue=0;

while(defined($INPUT[$cnt]))
{
        while (my @instance = $q1->fetchrow_array)
        {
                my $walk = "string";
                push @{$QUEUES{$current_queue}},$walk;
                $current_queue=($current_queue+1)%$thread_count;
        }

        while (my @instance = $q2->fetchrow_array) {
                my $walk = "string";
                push @{$QUEUES{$current_queue}},$walk;
                $current_queue=($current_queue+1)%$thread_count;
        }
}

我试图将命令推送到一个数组中,我决定将其保存在一个哈希中,因为我认为我可以让我的生活变得轻松而不是这样做if(!defined($QUEUES[$current_queue]))$QUEUES[$current_queue]=[];

我使用Data::Dumper了一个常规的 for 循环,发现没有为 $QUEUE 中的任何键定义任何内容,从 0 到 $thread_count-1。这不是教科书自动复活的用法吗?我究竟做错了什么?

4

1 回答 1

3
push @{ $QUEUES{$current_queue} }, $walk;

相当于

push @{ $QUEUES{$current_queue} //= [] }, $walk;

如果该语句在$QUEUES{$current_queue}不存在时被执行,$QUEUES{$current_queue}则将被创建,并为其分配一个对具有一个元素的数组的引用(的副本$walk)。

因此,如果%QUEUES为空,则push语句永远不会执行。

于 2016-02-02T12:34:53.583 回答