zentara has asked for the wisdom of the Perl Monks concerning the following question:
Hi, I recently had a need to run an loop and each time thru the loop I needed to alternatively add or subtract a variable. So I came up with:
I have a feeling that there is some "golfed way" of doing this in a more simple fashion. I thought about taking the output of rand, and make the number 1 if > .5 and -1 if less than .5. Anyone have ideas? Thanks.#!/usr/bin/perl @hits = (-1,1); for(1..10){ print toggle(),"\n"; } sub toggle{ push (@hits,shift(@hits)); return $hits[0]; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: random negative toggle function
by !1 (Hermit) on Nov 15, 2003 at 19:37 UTC | |
|
Re: random negative toggle function
by Limbic~Region (Chancellor) on Nov 15, 2003 at 19:14 UTC | |
|
Re: random negative toggle function
by jeffa (Bishop) on Nov 15, 2003 at 21:26 UTC | |
|
Re: negative toggle function
by CombatSquirrel (Hermit) on Nov 15, 2003 at 18:06 UTC | |
|
Re: negative toggle function
by EdwardG (Vicar) on Nov 15, 2003 at 18:43 UTC | |
|
Re: random negative toggle function
by EdwardG (Vicar) on Nov 15, 2003 at 19:06 UTC | |
|
Re: random negative toggle function
by zentara (Cardinal) on Nov 16, 2003 at 22:50 UTC |