I have this segment of a perl script:
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;
}
}
I was trying to push commands in an array, which I decided to keep in a hash because I thought I could keep my life easy and not do if(!defined($QUEUES[$current_queue]))$QUEUES[$current_queue]=[];
I used Data::Dumper
and a regular for loop and found that nothing was defined for any key in $QUEUE, 0 to $thread_count-1. Isn't this a textbook auto-vivification usage? What am I doing wrong?
push @{ $QUEUES{$current_queue} }, $walk;
is equivalent to
push @{ $QUEUES{$current_queue} //= [] }, $walk;
If that statement got executed when $QUEUES{$current_queue}
didn't exist, $QUEUES{$current_queue}
would get created, and it would be assigned a reference to an array with one element (a copy of $walk
).
So, if %QUEUES
is empty, then the push
statements were never executed.