Saturday, December 28, 2019
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.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.