I've finally started reading Object Oriented Perl by Damien Conway and am enjoying it tremendously. Taking some of his code, I use a closure to create a simple binary toggle (something similar was discussed in this node).

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; } }

Replies are listed 'Best First'.
RE: Easy binary toggle at fixed intervals
by extremely (Priest) on Oct 21, 2000 at 11:45 UTC
    Sexy! I likey a lot. Still, I had to tinker...
    #!/usr/bin/perl -w use strict; my $cycle = initToggle( 3 ); for (1..24) { print "$_ " . &$cycle . "\n"; } sub initToggle { my $limit = shift; die "initToggle() requires a non-zero integer\n" if ($limit == 0 or int($limit) != $limit); my $count = -1; my $bit = $limit >0 ? 0 : 1; $limit = abs($limit); return sub { $bit ^=1 if (++$count % $limit == 0); return $bit; } }

    Now you can flip the bit on creation and you check for initToggle ( 3.333 );

    --
    $you = new YOU;
    honk() if $you->love(perl)