Why aren't my push and pop methods working?
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
@ar开发者_运维问答ray = 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";
First things first, use use strict; use warnings;
.
What's pop @array, 4;
supposed to do?
Pop four elements?
splice(@array, -4);
Replace the last element with the value 4?
$array[-1] = 4;
Filter out the value 4?
@array = grep { $_ != 4 } @array;
Reference:
pop
splice
grep
By the way, #usr/bin/perl
is meaningless. It should be #!/usr/bin/perl
.
By the way, the escape sequence for a newline is \n
, not /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.)
#!/usr/bin/perl
use strict;
use warnings;
my @array = 1..5;
push @array, 6;
push @array, 7;
my $top = pop @array;
print "Top was $top\n";
print "Remainder of array is ", join(", ", @array), "\n";
Incorrect syntax: pop @array, 4;
pop should take at most, one argument (the array). It will pop the last element from the array stack, whereas shift takes the first element from the stack.
精彩评论