Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

String manipulation

by hotshot (Prior)
on Aug 01, 2004 at 13:24 UTC ( #379063=perlquestion: print w/replies, xml ) Need Help??

hotshot has asked for the wisdom of the Perl Monks concerning the following question:

Hello again!

I have three arguments: initial value, step and number of members. I need to create a string as follows:
# for example: $initValue = 2; $step = 3; $numOfMembers = 5; # wanted string is: $str = '2 5 8 11 14';
Like arithmetic sequence. How can I create the string efficiently?
Of course I can do:
my $str = $initValue; for (my $i=2; $i<=$numOfMembers; $i+=$step) { $str .= ' ' . ($initValue + $step($i-1)); }
But I'm sure there's elegant ways than that.
If it matters or not, $step will always be 1 or 2 (according to another parameter I have lets say ($isDoubleStep)).


Replies are listed 'Best First'.
Re: String manipulation
by Ovid (Cardinal) on Aug 01, 2004 at 13:48 UTC

    Elegance, of course, is in the eye of the beholder.

    my $init = 1; my $step = 4; my $count = 5; + my $string = join ' ' => map { $_ * $step - ($step - $init) } 1 .. $count;

    If your code works, there's nothing wrong with it.


    New address of my CGI Course.

      My code is working, but what about effieciency and performance, is there a difference between the for loop in my suggestion to map?

        You'll find many nodes on the topic of performance optimization. Let me summarize all of them for you: don't optimize unless you need to.

        One of the biggest issues programmers face (myself included) is the tendency to say "this won't run fast so I had better speed it up." The reality is, if it runs fast enough, it runs fast enough. Particularly as a system gets large, it becomes more and more difficult to guess what will really speed things up. Even if you speed up a loop 100 times, if the program only spends one percent of its time there you've likely wasted your effort.

        But optimizing isn't really bad, is it? I mean, if I optimize everything won't my program will run really fast?

        The answer to that is a resounding NO! I can't recall offhand who said it, but one telling quote is "it's easier to optimize correct code than to correct optimized code." Every hoop you jump through to squeeze out every little bit of performance is another chance for your foot to catch on that hoop and make you stumble. You'll likely introduce more bugs and you'll simply waste time trying to second guess whether or not a particular construct can be faster when what you really want to be doing is delivering product. You'll also be more likely to obfuscate your code and make maintenance more difficult. Only when you have a deliverable and you can get an idea how it's likely to be used in a production environment can you really begin to start performance profiling to find out where the bottlenecks, if any, are.

        In summary, do not fall into the time-wasting trap of second guessing the performance of your code. Make your code correct and only when you really have a performance problem should you start profiling things. With a performance profile in hand, then you can know where you should be optimizing instead of guessing.

        (Note: the above is good general advice and there are definitely times it should be ignored, but once you get to the point where you can make the distinction you'll be giving others this advice :)


        New address of my CGI Course.

        My code is working

        Try and run it. It does not compile.

        My code is working

        Fix the compiler errors and then fix the logical errors so it produces what you say it should.

        My code is working

        Your code is most certainly not working. Just look at the loop and tell me how many loops you will get for $step = 1000 and numOfMembers = 1000. I get 1 loop, how about you? Don't see that adding 1000 members......

        for (my $i=2; $i<=$numOfMembers; $i+=$step) {



        Try this code :
      #!/usr/bin/perl -w use strict; my ($initValue,$step,$numOfMembers,$str) = (2,3,5,''); foreach(1..$numOfMembers) { $str.= (/1/)?$initValue:' '.$initValue; $initValue+=$step; } print "$str\n";
      Cheers !
        Bipin Balan
Re: String manipulation
by leriksen (Curate) on Aug 01, 2004 at 13:45 UTC
    my $str = join(' ', map {$initValue + $_ * $step} (0..$numOfMembers-1) +);

    use brain;

Re: String manipulation
by tachyon (Chancellor) on Aug 01, 2004 at 13:57 UTC

    Well given that your posted code does not work (does not compile and is logically incorrect), this is similar, efficient and working:

    $initValue = 2; $step = 3; $numOfMembers = 5; $str = '2 5 8 11 14'; my $str = $initValue; for my $member (1..$numOfMembers-1) { $str .= ' ' . ($initValue + $member*$step); } print $str, $/; $str = join ' ', map{ $initValue+$step*$_ } 0..$numOfMembers-1; print $str, $/;



Re: String manipulation
by Aristotle (Chancellor) on Aug 01, 2004 at 16:00 UTC

    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.

      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? ;)

Re: String manipulation
by BbTrumpet (Acolyte) on Aug 02, 2004 at 18:07 UTC
    A hack from a not-an-expert Perl user, but it works:
    use strict; my $initValue = 3; my $step = 3; my $numOfMembers = 25; my $str = ""; my $ix; for($ix = $initValue; $ix <= $initValue + $step * ($numOfMembers - 1); $ix += $step) { $str .= $str eq "" ? $ix : " $ix"; } ### TEST ### print "'$str'\n";

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://379063]
Approved by dsb
Front-paged by VSarkiss
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2023-11-29 16:24 GMT
Find Nodes?
    Voting Booth?

    No recent polls found