#!/usr/bin/perl -w use strict; print "Content-type: text/plain\n\n"; sub outer { my ($a) = @_; my $b = "sophie"; my $d = "sam"; print "at start of outer: \n"; print " a = '$a' \n"; # This is a closure - a reference to an anonymous code block. # It has access to all the lexical variables in scope at # the moment of its definition. my $innerFunc = sub { print " -- innerFunc \n"; print " a is '$a' \n"; print " b is '$b' \n"; print " passed in: ", @_, "\n"; print " this copy of d is '$d' \n"; $a = $a . " - modified"; $d = $d . " - changed"; }; # The loop variable $d in this for loop doesn't behave # the way I expected. Apparently, to keep the value # (i.e. 'sam') undisturbed when the loop exists, the "foreach" # creates another scalar value, and points $d at that new scalar # value while the loop is running. Then at the end, it points $d # back at the original value. But the value of $d within the # closure still refers to the original, "real" value - it doesn't # see the "one", "two", "three" we're looping over. foreach $d ( qw( one two three) ) { my $c = $d . "ish"; $b = $c x 2; print " getting ready to call inner - within loop, d = '$d' \n"; $innerFunc->( $c ); print "\n"; } print " back in outer, outside loop : \n"; print " a is '$a' \n"; print " b is '$b' \n"; print " d is '$d' \n"; } outer( "Tom" );