Andrew Curry wrote:
>> -----Original Message-----
>> rom: J. Peng [mailto:[EMAIL PROTECTED] 
> Sent: 01 May 2008 15:31
> To: [EMAIL PROTECTED]
> Cc: beginners@perl.org
> Subject: Re: question on foreach loop
> 
> To add a statement of "print $_" follow the foreach, you will see what
> was happening.
> 
> foreach (@data){
>    print "$_\n";
>    splice @data,0,1;
>    print "printing [EMAIL PROTECTED] = @data\n";
> }
> 
> On Thu, May 1, 2008 at 10:15 PM,  <[EMAIL PROTECTED]> wrote:
>> Hi Members,
>>  Can someone explain why the foreach loop did not iterate 10 times.
>>
>>  Thanks
>>
>>  #################
>>  use strict;
>>  use warnings;
>>
>>  my @data = (1..10);
>>
>>  foreach (@data){
>>     splice @data,0,1;
>>     print "printing [EMAIL PROTECTED] = @data\n";  }
>>
>>  ##### results ###########
>>  printing @data = 2 3 4 5 6 7 8 9 10
>>  printing @data = 3 4 5 6 7 8 9 10
>>  printing @data = 4 5 6 7 8 9 10
>>  printing @data = 5 6 7 8 9 10
>>  printing @data = 6 7 8 9 10
> 
> Is not what is exactly expected
> 
> Removes the elements designated by OFFSET and LENGTH
>              from an array, and replaces them with the elements
>              of LIST, if any.  
> So above...
> 
> ON @data 1,2,3,4,5,6,7,8,9,10#
> Remove 0,1 (1) so.... 
> printing @data = 2 3 4 5 6 7 8 9 10
> 
> ON @data 2,3,4,5,6,7,8,9,10
> Remove 2
> printing @data = 3 4 5 6 7 8 9 10
> 
> 
> ON @data 3,4,5,6,7,8,9,10
> Remove 3
> printing @data = 4 5 6 7 8 9 10
> 
> ON @data 4,5,6,7,8,9,10
> Remove 4
> printing @data = 5 6 7 8 9 10
> 
> ON @data 5,6,7,8,9,10
> Remove 5
> printing @data = 6 7 8 9 10
> 
> As the iterator of foreach has been modified once by the foreach and
> once by the splice it thinks it has nothing more to process?

It's best just to take it as read that if you modify the array that foreach is
interating over then the results are undefined. You should never do it, if only
because the actual behaviour may well vary for different versions or builds of
Perl, and possibly even for the same version on different platforms. Indeed it's
not ruled out that the same build on the same platform could behave differently
on two identical runs.

If you want a way of understanding why you are seeing these results, then how
about this: foreach has executed five iterations, and there are only five
elements in the array, so it's all done.

Rob

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to