Pass the sub a positive integer, $x, and it returns an anonymous sub that automatically toggles between 1 and 0 every $x times it's accessed. The following snippet illustrates its use.
Update: Made a slight change so that $count could start at zero instead of negative one. I also liked extremely's use of the ternary ( w = x ? y : z ) operator to set $bit!
#!/usr/bin/perl -w use strict; my $cycle = initToggle( 3 ); for ( 1 .. 24 ) { print "$_\t" . &$cycle . "\n"; } sub initToggle { my $limit = shift; my $count = 0; my $bit = 0; unless ( $limit > 0 ) { die "initToggle() requires a positive argu +ment\n" }; return sub { $bit ^= 1 if $count++ % $limit == 0; return $bit; } }
In reply to Easy binary toggle at fixed intervals by Ovid
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |