Hi Everyone!

I have here a queue:

my $qTool = Thread::Queue->new();

I want to show all the elements that the queue contains.

my $qItem = $qTool->peek();

The code above returns only either the head of the queue or an element at a specified index.

Is there a way for me to show all the elements instead of only one?
For example, if the queue contains ,
"->peek()" only returns 'item1'.
"->peek(1)" returns 'item2'.


Any help would be appreciated.
Thanks.

If you show the code what you have tried, it could be more useful to analyze and give the suggestions on this.

The pending method gives you the number of items in the queue, so you can peek at each of them in a loop.

#!/usr/bin/perl
use strict;
use warnings;

use Thread::Queue;
my $q = new Thread::Queue;
$q->enqueue('item1', 'item2', 'item3');

my $count = $q->pending;
my @queued_items;
push @queued_items, $q->peek($_) foreach(0 .. $count-1);

print "Items currently in queue:\n";
print  join "\n", @queued_items;
Comments
Well Understand & Nice Example
Very straightforward. thanks!

Thanks d5e5!

I was also using the pending method in my program however it was only for dequeueing items from the queue. Thanks for showing how to use it by printing the items in the queue with the help of the peek method.

I did found a way to print the items in the queue yesterday simply by using Data:: Dumper

print "Items currently in queue: ";
print Dumper $q;

However, I didn't know how to omit "bless" and 'Thread::Queue', and here was the result:

Items currently in queue: bless( ["item1","item2","item3"], 'Thread::Queue' )

Anyway, just wanted to share what I had to do to print the queued items. Thanks again! :)

You're welcome. Technically, you might get away with

print join "\n", @{$q}; #Not recommended. I'm not sure why this works (for me).

but it's safer to use one of the object's methods instead of figuring out the internal structure of the object, which may vary depending on the version of the Thread::Queue module.

Comments
Thanks again for the insight!
This question has already been answered. Start a new discussion instead.