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

Hi, im writing a script which runs the code within a while loop for a specified "time duration" as opposed to the "number of times".
$_current_time = time(); $_new_time = $_current_time + $_time_offset; while ($_current_time < $_new_time ){ execute_attack($random_rate); }
Im getting stuck at the while loop for obvious reasons being that $_current_time is relatively always lesser than $_new_time as the time() function updates both variables. i need the while loop to run only for the $_time_offset period. how could i better approach this. Thanks in Advance!

Replies are listed 'Best First'.
Re: loop execution for "time" specified
by gwadej (Chaplain) on Mar 24, 2009 at 13:27 UTC

    In the code above, $_current_time is never updated, so you loop forever.

    Change your condition to time < $_new_time.

    G. Wade
      thank you.The code is working just fine now!
Re: loop execution for "time" specified
by Limbic~Region (Chancellor) on Mar 24, 2009 at 14:40 UTC
    perlpal,
    The obvious problem has already been pointed out to you, but there are some additional things you might want to consider. For instance, if $_time_offset is a negative number, you still introduce an infinite loop. Additionally, you have no sleep before the next iteration of your loop. If execute_attack() doesn't do as you expect, this could turn into a runaway CPU hog. On the other hand, if execute_attack() itself becomes a long running process - you still may run longer than you want - see alarm and %SIG in perlvar for a potential solution.

    You should be able to take the ideas I am providing and build on them. If you don't understand or come up short, come back and ask for more help - but keep in mind that with a sub name like execute_attack(), we will likely want a better explanation of what your code is doing before helping further.

    Cheers - L~R

Re: loop execution for "time" specified
by MidLifeXis (Monsignor) on Mar 24, 2009 at 13:28 UTC

    You set $_current_time before the loop starts - it is the current time before you enter the while loop. (1) What would you need to check to get the current time at the point where you do the comparison, and (2) how could you change your code (one line only) to implement (1).

    --MidLifeXis

    The tomes, scrolls etc are dusty because they reside in a dusty old house, not because they're unused. --hangon in this post