Zen and the Art of Perl

| No Comments | No TrackBacks

On the oppositeness of pop, push, shift and unshift with Perl


I had reason to use
perl -f unshift

unshift ARRAY,LIST 
     Does the opposite of a "shift". Or the opposite of a "push", depending on how you look
     at it. Prepends list to the front of the array, and returns the new number of elements in
     the array. 
         unshift(@ARGV, '-e') unless $ARGV[0] =~ /^-/; 
     Note the LIST is prepended whole, not one element at a time, so the prepended
     elements stay in the same order. Use "reverse" to do the reverse.
The second sentence piqued my curiosity enough to check the differences between shift, unshift, push and pop. After all, surely an unshift operation was the same as a push operation?

I already knew that shift pops off the front of the array and I learned unshift pushes onto the front of the array.  The opposite-ness is clear.  

I was familiar with the concept of pop and push w.r.t stack operations, pop something on to the stack and pop it off ... anyone remember the postfix (reverse Polish) notation exercises in their CS A-Level?

In Perl, pop pops off the end of the array and push pushes onto the end of the array.  And that provides a different kind of oppositeness to unshift/shift operations.  

I misinterpreted the second sentence on the basis of previously stored information.

The use of pop/push and shift/unshift in other languages is quite common.  It's not just a Perl thing.  

No TrackBacks

TrackBack URL: http://herlug.org.uk/mt/mt-tb.cgi/15

Leave a comment

About this Entry

This page contains a single entry by Lesley published on September 22, 2011 3:09 PM.

Debian Women Mentoring Scheme was the previous entry in this blog.

T-shirts, workshops and conferences is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.