Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions

  




 

 

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.4.2.2 Arrays as Queues

If we can do stacks, then why not queues? You can build a queue in Perl by using the unshift and pop functions together.(9) Think of the unshift function as "enqueue" and the pop function as "dequeue". Here is an example:

use strict; my @queue; unshift (@queue, "Customer 1"); # @queue is now ("Customer 1") unshift (@queue, "Customer 2"); # @queue is now ("Customer 2" "Customer 1") unshift (@queue, "Customer 3"); # @queue is now ("Customer 3" "Customer 2" "Customer 1") my $item = pop(@queue); # @queue is now ("Customer 3" "Customer 2") print "Servicing $item\n"; # prints: Servicing Customer 1\n $item = pop(@queue); # @queue is now ("Customer 3") print "Servicing $item\n"; # prints: Servicing Customer 2\n

This queue example works because unshift places items onto the front of the array, and pop takes items from the end of the array. However, be careful using more than two arguments on the unshift when you want to process an array as a queue. Recall that unshift places its arguments onto the array in order as they are listed in the function call. Consider this example:

use strict; my @notAqueue; unshift(@notAqueue, "Customer 0", "Customer 1"); # @queue is now ("Customer 0", "Customer 1") unshift (@notAqueue, "Customer 2"); # @queue is now ("Customer 2", "Customer 0", "Customer 1")

Notice that this variable, @notAqueue, is not really a queue, if we use pop to remove items. The moral here is to be careful when using unshift in this manner, since it places it arguments on the array in order.




 
 
  Published under the terms of the GNU General Public License Design by Interspire