Ovid has asked for the wisdom of the Perl Monks concerning the following question:
The above snippet happily prints 0,1,0,1,0,1 on successive lines. However, every time I try to pass $toggle to a subroutine from doStuff(), it gets turned to a scalar. How do I get it to pass itself as a code reference? I'm using this to encapsulate some functionality in a module and I don't want to declare $toggle globally.#!/usr/bin/perl -w use strict; doStuff(); sub doStuff { my $toggle = initToggle( 1 ); for ( 1..6 ) { print &$toggle . "\n" }; } sub initToggle { my $x = shift; return sub { $x ^= 1; return $x }; }
Further, I'm not looking for a better way to toggle values. This is just something I'm doing to understand closures better.
Cheers,
Ovid
Join the Perlmonks Setiathome Group or just go the the link and check out our stats.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Closures question
by btrott (Parson) on Oct 20, 2000 at 01:29 UTC | |
by cianoz (Friar) on Oct 20, 2000 at 01:40 UTC | |
by btrott (Parson) on Oct 20, 2000 at 02:04 UTC | |
|
(Ovid) Re: Closures question
by Ovid (Cardinal) on Oct 20, 2000 at 02:10 UTC | |
|
Re: Closures question
by chromatic (Archbishop) on Oct 20, 2000 at 01:51 UTC | |
|
Re: Closures question
by cianoz (Friar) on Oct 20, 2000 at 01:29 UTC |