Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!elroy.jpl.nasa.gov!jpl-devvax!lwall From: lwall@jpl-devvax.jpl.nasa.gov (Larry Wall) Newsgroups: comp.lang.perl Subject: Re: Add 'continue' to 'foreach'? Message-ID: <1991May8.171226.28571@jpl-devvax.jpl.nasa.gov> Date: 8 May 91 17:12:26 GMT References: <1991May8.015608.19707@uvaarpa.Virginia.EDU> Reply-To: lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) Organization: Jet Propulsion Laboratory, Pasadena, CA Lines: 77 In article <1991May8.015608.19707@uvaarpa.Virginia.EDU> bjaspan@ATHENA.MIT.EDU writes: : How about adding an optional continue block to the foreach statement? : Then I could do something like this: : : $i = 0 : foreach (@rdset) { : next unless $_; : : # stuff : } continue { : $i++; : } : : The advantage to doing it this way is that foreach is non-destructive. : Doing it with a while (which has a continue block) would require : shifting the array, which (1) would mean I couldn't use it again, or I : would have to keep a copy, and (2) I would guess is slower than just : iterating over the elements. Before asking for a new feature, you might check to see if it's already there. :-) I just said: foreach (1..10) { print "$i\n" unless $_ & 1; } continue { $i++; } and it said 1 3 5 9 : As a separate issue, I just thought of another way to do it (after : all, this is perl): : : $rdstr = unpack('b*', $rdset); : $i = length($rdstr); : while (chop $rdstr) { : next unless $_; : # stuff : } continue { $i--; } : : This saves a split(), and adds a length() and a bunch of chop()s; it : also iterates backwards (although this doesn't matter in this : particular case). Is this faster? (ie: how fast is chop?) I suspect it's faster, but Perl programming is an empirical science. (Actually, I suspect that it doesn't work, since "while (chop $rdstr)" is not going to assign to $_. Say "while ($_ = chop $rdstr)" instead. (Actually, that won't work either, since "0" is false.)) The chop operator itself is quite fast. I'd write it like this if I wanted to use chop: while ($rdstr ne '') { next unless chop $rdstr; # stuff } continue { $i--; } Howsomever, I wouldn't use chop, especially when most of the bits are going to be 0. I'd say for ($fd = index($rdstr,'1'); $fd >= 0; $fd = index($rdstr,'1',$fd+1)) { # stuff } It's almost always a mistake to write a linear search algorithm in Perl. Let Perl do the searching for you. Larry