954,523 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

View Items in the queue using Thread::Queue

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 ['item1', 'item2', 'item3'],[INDENT]"->peek()" only returns 'item1'.[/INDENT][INDENT]"->peek(1)" returns 'item2'.[/INDENT]

Any help would be appreciated.
Thanks.

gutchi
Newbie Poster
7 posts since Dec 2009
Reputation Points: 10
Solved Threads: 0
 


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

k_manimuthu
Junior Poster in Training
93 posts since Jun 2009
Reputation Points: 55
Solved Threads: 24
 

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;
d5e5
Practically a Posting Shark
810 posts since Sep 2009
Reputation Points: 159
Solved Threads: 159
 

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! :)

gutchi
Newbie Poster
7 posts since Dec 2009
Reputation Points: 10
Solved Threads: 0
 

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.

d5e5
Practically a Posting Shark
810 posts since Sep 2009
Reputation Points: 159
Solved Threads: 159
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: