我希望通过使用数组和数组顶部编写代码来实现perl函数的push
和pop
功能。
例如:pop
将弹出最后一个元素。但是如何通过获取数组的最后一个值来实现呢?
我写了下面的代码,但似乎不起作用。
#!/usr/bin/perl
$in = $1;
sub push {
my $top = 0;
@stack=("a","b","c");
my $max = 20;
print "Push: @stack.";
if($top = $max - 1) {
print "Overflow";
}
else {
$stack[$top] = $in;
$top = $top + 1;
print "After Push: @stack.";
}
print "Before Pop: @stack.";
my $new=$stack[$top];
$top = $top - 1;
print "Popped item: $new.";
print "After Pop: @stack.";
}
答案 0 :(得分:0)
你没有说你想做什么,所以我们不能告诉你你是否这样做。但看起来您写的内容可以使用push
和pop
更清晰地写出来。
my $stack_size = 20;
my @stack;
sub push_onto_stack {
my ($item) = @_;
die "Overflow\n" if @stack > $stack_size;
push @stack, $item;
}
sub pop_from_stack {
die "Stack empty\n" if !@stack;
return pop @stack;
}
如果这是一项要求避免使用push
和pop
的作业,那么您可以使用
$stack[@stack] = $item; # push @stack, $item
和
my $item = $stack[-1]; --$#stack; # my $item = pop @stack;
答案 1 :(得分:0)
我编写的代码如下:
#!/usr/bin/perl
use strict;
use warnings;
our @stack=("this","is","a","basic","example");
our $top = $#stack;
sub push_test {
my $max = 7;
print "\nCurrent Stack is: @stack\n";
if($top == $max - 1)
{
print "\nScript Overflown. Testing others.\n";
}
else
{
$stack[@stack] = $in;
$top+=1;
print "After Push Stack is: @stack\n";
}
}
sub pop_test {
print "\nBefore Pop Stack is: @stack.\n";
my $new = $stack[-1];
--$#stack;
print "Poped item is: $new.\n";
print "After Pop Stack is: @stack\n";
}
sub peek_test {
my $peek = $stack[0];
print "\nPeek element is: $peek\n";
}
sub empty_test {
print "\nTop value: $top.\n";
if ($top == -1)
{
print "Array is empty.\n";
}
else
{
print "Array is not empty.\n";
}
}
foreach $i (@ARGV){
$in=$i;
print "\nTESTING SCRIPT";
print "\nTest: Push";
push_test($in);
}
print "\nTest: Pop";
pop_test();
print "\nTest: Peek";
peek_test();
print "\nTest: Is_empty";
empty_test();
exit;