in reply to foreach .. stepping?

For syntax, though not efficiency, try:
sub step { my $step = shift; return grep {($_ - $_[0]) % $step == 0} @_ } foreach (step 5, 2 .. 100) { print "$_ " }
which prints:
2 7 12 17 22 27 32 37 42 47 52 57 62 67 72 77 82 87 92 97

Replies are listed 'Best First'.
Re: Re: foreach .. stepping?n
by mce (Curate) on Nov 20, 2002 at 13:39 UTC
    Hi,

    But the fastest solution is using a closure:

    sub step { my $step=shift; my $count=0; my @array=@_; return sub { $return=$array[$count]; $count+=$step; return $return }; }; for ( my $s=step(5,2..100); my $res=&$s ; 1 ) { print "$res "; }
    My benchmark shows 6 times faster than the map, and 10 times faster than the step method.

    The reason is that I transfer an array only once, and than do queries in the array, whilst with map or step, one iterates over more than one array (map/grep and foreach).
    ---------------------------
    Dr. Mark Ceulemans
    Senior Consultant
    IT Masters, Belgium