I’m trying to implement a stack in Perl where I have an array. I want to push items on the array, pop items out and print out the new array like so: “1,2,3,5,6
How can I do that? My code just adds the number 6 to the top of the array.
#!usr/bin/perl
@array = 1..5;
push @array, 6; #Push the number 6 into the array
pop @array, 4; #Pop the number 4 out of the array
print "The array is now $array[-1].\n";
The whole point of a stack is you can only access items from the top. You can only push an item onto the top of stack or pop an item off the top of the stack. The elements in the middle are not accessible. Using Perl’s shift and unshift functions you can also implement queues and dequeues (or double-ended queues.)