Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How does shift() work within a loop?

Status
Not open for further replies.

webgeo

Technical User
Mar 4, 2003
4
RO
I am trying to create something like the following, which will loop through an array and simultaneously remove the first value from the array each time:

Code:
@array = (1,2,3,4,5,6);

foreach $value (@array)
{
  shift(@array);  ## used elsewhere
  print "$value";
}

My problem is that the printed output is 1,3,5 instead of 1,2,3,4,5,6.

Why am I only getting every second value? I assume the "foreach" is doing some sort of internal shift but how do I get around it?

Any help much appreciated!

Thanks in advance.
 
The result you're getting is probably based on perl keeping track of the current index in the list for the [tt]foreach[/tt]. You're shifting off the first value, so the index is no longer correct.

What you probably want to do is something like (instead of the [tt]foreach[/tt]:
[tt]while ($value = shift @array) {
print "$value";
}
[/tt]
 
Worked a treat! Obvious really - doh! Many thanks.
 
The other side of the same coin is just
[tt]foreach my $value (@array) {
print $value;
}[/tt]
or, (this being perl), even
[tt]foreach (@array) {
print $_;
}[/tt]
or, minimally,
[tt]print for (@array);[/tt] "As soon as we started programming, we found to our surprise that it wasn't as
easy to get programs right as we had thought. Debugging had to be discovered.
I can remember the exact instant when I realized that a large part of my life
from then on was going to be spent in finding mistakes in my own programs."
--Maurice Wilk
 
True. Why the shift is in there is a good question. Just do the [tt]foreach[/tt] and then set [tt]@array = ();[/tt] afterwards is the same thing.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top