I need to be able to maintain a stack which varies in length according to circumstances. I want to use shift() and unshift() at the left, and push() and pop() at the right.
I have noticed strange behaviour when using shift(). My simple example below shows the problem.
In this example, when I use shift() "manually", the stack is correctly shifted five times. But when I use "for" or "foreach", the stack is only shifted three times. When I check the remaining contents of the stack, "four" and "five" are still present.
I would be grateful if anyone could explain this.
Forum users probably know many other ways to accomplish the same objective, but I would prefer to learn why shift() does not work the correct number of times (5).
Regards,
Alan
#------------------------------
#!/usr/bin/perl -w
my @stack = qw(one two three four five) ;
print ( shift ( @stack). "\n" ) ;
print ( shift ( @stack). "\n" ) ;
print ( shift ( @stack). "\n" ) ;
print ( shift ( @stack). "\n" ) ;
print ( shift ( @stack). "\n" ) ;
print "-----------------\n";
@stack = qw(one two three four five) ;
foreach ( @stack )
{
print ( shift ( @stack). "\n" ) ;
}
print "-----------------\n";
@stack = qw(one two three four five) ;
my $numStackEntries = @stack ;
my $i ;
for ( $i = 0 , $i < $numStackEntries, $i++ )
{
print ( shift ( @stack). "\n" ) ;
}
I have noticed strange behaviour when using shift(). My simple example below shows the problem.
In this example, when I use shift() "manually", the stack is correctly shifted five times. But when I use "for" or "foreach", the stack is only shifted three times. When I check the remaining contents of the stack, "four" and "five" are still present.
I would be grateful if anyone could explain this.
Forum users probably know many other ways to accomplish the same objective, but I would prefer to learn why shift() does not work the correct number of times (5).
Regards,
Alan
#------------------------------
#!/usr/bin/perl -w
my @stack = qw(one two three four five) ;
print ( shift ( @stack). "\n" ) ;
print ( shift ( @stack). "\n" ) ;
print ( shift ( @stack). "\n" ) ;
print ( shift ( @stack). "\n" ) ;
print ( shift ( @stack). "\n" ) ;
print "-----------------\n";
@stack = qw(one two three four five) ;
foreach ( @stack )
{
print ( shift ( @stack). "\n" ) ;
}
print "-----------------\n";
@stack = qw(one two three four five) ;
my $numStackEntries = @stack ;
my $i ;
for ( $i = 0 , $i < $numStackEntries, $i++ )
{
print ( shift ( @stack). "\n" ) ;
}