xandercrews has asked for the wisdom of the Perl Monks concerning the following question:
yields:#!/usr/bin/perl -- use strict; # use warnings; sub factoryOne { my ($var) = (@_); print "factory: '$var'\n"; return sub { eval { print "eval: '$var'\n" }; } } sub factoryTwo { my ($var) = (@_); print "factory: '$var'\n"; return sub { my $estr = "print \"eval: '\$var'\n\""; eval $estr; } } sub factoryThree { my ($var) = (@_); print "factory: '$var'\n"; return sub { $var; my $estr = "print \"eval: '\$var'\n\""; eval $estr; } } my $f = factoryOne('lulz'); $f->(); my $g = factoryTwo('frunz'); $g->(); my $h = factoryThree('lulz'); $h->();
factory: 'lulz' eval: 'lulz' factory: 'frunz' eval: '' factory: 'lulz' eval: 'lulz'
the first factory works as expected, the second two don't, really.
two questions:
1) why isn't $var in scope inside the eval inside the closure inside factoryTwo?
2) why does referencing $var in the closure remedy 1) in factoryThree?
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: i don't understand this scope behavior w/ closures and eval
by ikegami (Patriarch) on Feb 11, 2010 at 22:51 UTC | |
by ambrus (Abbot) on Feb 12, 2010 at 20:46 UTC | |
Re: i don't understand this scope behavior w/ closures and eval
by jethro (Monsignor) on Feb 11, 2010 at 22:23 UTC | |
Re: i don't understand this scope behavior w/ closures and eval
by crashtest (Curate) on Feb 11, 2010 at 22:33 UTC |