Sunday, October 20, 2019

How to Use the Perl Array Push() Function

How to Use the Perl Array Push() Function The Perl  push()  function is used to push a value or values onto the end of an array, which increases the number of elements. The new  values  then become the  last elements  in the array. It returns the new total number of elements in the array. Its easy to confuse this function with  the  unshift()  function, which adds elements to the  beginning  of an array. Heres an  example of the Perl push() function: myNames (Larry, Curly);push myNames, Moe;print myNames\n; When this code is executed, it delivers: Larry Curly Moe Picture a row of numbered boxes, going from left to right. The push() function pushes the new value or values onto the right side of the array  and increases the elements.   The array can also be thought of as a stack. Picture a stack of numbered boxes, starting with 0 at the top and increasing as it goes down. The push() function pushes the value onto the bottom of the stack  and increases the elements, like this: myNames (Larry,Curly);push myNames, Moe; You can also push multiple values onto the array directly ... myNames (Larry, Curly);push myNames, (Moe, Shemp); ... or by pushing on an array: myNames (Larry, Curly);moreNames (Moe, Shemp);push (myNames, moreNames); Note for beginning programmers:  Perl arrays begin with an symbol. Each complete line of code must end with a semicolon. If it doesnt, it wont execute. In the stacked example in this article, the lines without a semicolon are values contained in an array and enclosed in parentheses. This isnt an exception to the semicolon rule, as much as a result of the stack approach. The values in the array are not individual lines of code. It is easier to picture this in the horizontal approach to coding. Other Functions for Manipulating Arrays Other functions are also used to manipulate arrays. These make it easy and efficient to use a Perl array as a stack or as a queue. In addition to the push function, you can use: Pop function – removes and returns the last element of an arrayShift function – moves the whole array to the left. The element that is the first element of the array falls off the array and becomes the return value of the functionUnshift function – the opposite of the shift function, places a value at the beginning of an array and moves all the other element to the right.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.