Scope of variables in a function

Dave Mitchell davem at iabyn.com
Sun Jun 2 12:49:19 BST 2013


On Sat, Jun 01, 2013 at 10:19:11PM -0700, Yitzchak Scott-Thoennes wrote:
> On Sat, Jun 1, 2013 at 10:23 AM, Dirk Koopman <djk at tobit.co.uk> wrote:
> > Quite a lot of other perl artefacts have been deprecated and then removed.
> > Why does this one persist? In what way is it useful or intuitive?
> 
> Because it is the result of an optimization - lexicals are reset upon leaving
> scope, not entering it, and only if the my() was reached during execution.
> 
> Nevertheless, I believe Dave Mitchell had a patch to fix it that never
> quite made it in.

The original patch was a proof-of-concept that hoisted the run-time
effects of my to the start of the containing scope. So that from a
run-time point of view,

    {
	AAA;
	my $x = ...;
	BBB;
	my $y = ...;
	CCC;
	my $z = ...;
	DDD;

    }

is executed like

    {
	my ($x,$y,$y);
	AAA;
	$x = ...;
	BBB;
	$y = ...;
	CCC;
	$z = ...;
	DDD;
    }

The main problem with it was that in something like the following:

    while (<>) {
	next unless /rare condition/;
	my ($lots, $of, $lexicals) = split;
	...
    }

all those lexicals would be initialised and cleared every time round the
loop, rather than just on rare occasions: which could be quite a
performance hit.


-- 
Modern art:
    "That's easy, I could have done that!"
    "Ah, but you didn't!"


More information about the london.pm mailing list