On Monday 27 September 2010 10:17:16 HACKER Nora wrote:
> Hi Shlomi,
> 
> > You shouldn't modify an array (@arr1 in this case) while iterating
> 
> over it using
> 
> > foreach. Otherwise, the results will be unpredictable. One option to
> > overcome it is to do:
> > 
> > [code]
> > my @arr1_copy = @arr1;
> > 
> > while (defined (my $arr1_elem = shift(@arr1_copy))) {
> > 
> >     # Do something with $arr1_elem
> > 
> > }
> > [/code]
> 
> Is the principle you are trying to explain that the foreach loop should
> be changed to a while or that it is advisable to make a copy of the
> original array? (Or just both? :-) ) 

Well, if you don't care about the array being emptied (forever) by the loop, 
then you don't have to the «my @arr1_copy = @arr1;» thing and use the 
(while(defined loop on it as it is. Moreover, you shouldn't iterate on an 
array using *foreach* while changing the order of its elements (or removing 
them) because you'll get unexpected results. The "while shift" loop I've shown 
avoids such problems. 

> I suppose it's all about the
> 'while' because even if I made a copy of the array but continued with
> the foreach I would have the same problems, wouldn't I? Please confirm.
> 

Yes, you would.

> If not answered to the above question, please explain why it is
> advisable to make a copy of the original array?

Well, it is advisable if you want to preserve the original array. If not, you 
can use it as it is.

Regards,

        Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
Freecell Solver - http://fc-solve.berlios.de/

<rindolf> She's a hot chick. But she smokes.
<go|dfish> She can smoke as long as she's smokin'.

Please reply to list if it's a mailing list post - http://shlom.in/reply .

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to