in reply to String manipulation

If I'm not expecting this code to be used to generate strings with a huge number of members, I'd use an array.

sub number_sequence { my ($i, $step, $num) = @_; my @member = ( $i ); # caveat emptor: does not work if $num < 1; add guard if necessary push @member, $i += $step while --$num; return join " ", @member; }

In cases like this where calculations and string manipulation interleave, it's generally cleaner and more readable to separate the calculations from the string manipulation.

For small numbers of members this is even possibly more efficient than your code; but that isn't really a concern, as Ovid explained. What's more important to me is that this code is easier to change. I also prefer the iterative, additive approach over the multiplicative ones not for a desire for performance so much as one for minimalism on the conceptual level.

Makeshifts last the longest.

Replies are listed 'Best First'.
Re^2: String manipulation
by Jasper (Chaplain) on Aug 02, 2004 at 11:18 UTC
    I totally agree here. Adding step each time (instead of the multiplication) to the total is fundamentally a more simple and logical way to do this.

    Getting back to the OP, though, and while I think he's taken enough flak for posting broken code, why is $step 3 in the example when he states that it can be only 1 or 2? ;)