Node:Arrays as Queues, Previous:Arrays as Stacks, Up:Functions



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.1 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.


Footnotes

  1. For another way to do this, see the exercises in this section.