[LWN Logo]

From: Tom Christiansen <tchrist@mox.perl.com>
Subject: SRC: Nesting Subroutines
Date: 22 May 1998 13:42:17 GMT

If you're used to using nested subroutines in other programming
languages with their own private variables, you'll have to work at it a
bit in Perl.  The intuitive coding of this kind of thing incurs mysterious
warnings about ``will not stay shared''.  For example, this won't work:

    sub outer {
	my $x = $_[0] + 35;
	sub inner { return $x * 19 }   # WRONG
	return $x + inner();
    } 

A simple work-around is the following:

    sub outer {
	my $x = $_[0] + 35;
	local *inner = sub { return $x * 19 };
	return $x + inner();
    } 

--tom
-- 
/* This bit of chicanery makes a unary function followed by
   a parenthesis into a function with one argument, highest precedence. */
        --Larry Wall in toke.c from the perl source code