[comp.lang.perl] a bug in perl3.0pl44 related to "local

lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) (02/06/91)

In article <HIMAZU.91Feb5161554@isl.mei.co.jp> himazu@isl.mei.co.jp (IMAZU Hideyo) writes:
: The following code should produce
: 
: hello
: world
: 
: but it produces two null lines in my environment.
: Is this a feature of $_ or a bug?
: 
: &sub1;
: 
: sub sub0
: {
: 	local($_);
: 
: 	print $_[0], "\n";
: }
: 
: sub sub1
: {
: 	local($_);
: 
: 	foreach ( ('hello', 'world') ) {
: 		&sub0($_);
: 	}
: }

This is a "feature" of dynamic scoping when used with call-by-reference.
Don't do that.  :-)

This is why the Perl book recommends you always say

	local($_) = @_;

to pass in your arguments unless you are sure of what you're doing.
Since local() does dynamic scoping, the local() in sub0 is hiding the
value of $_ that was created by the foreach loop in sub1.  $_[0] is
a reference to $_, so it gets hidden as well.

I'd write these as:

	&sub1;

	sub sub0
	{
		local($_) = @_;

		print $_, "\n";
	}

	sub sub1
	{
		foreach ( ('hello', 'world') ) {
			&sub0($_);
		}
	}

Note that your local() in sub1 is useless, since foreach already localizes
its loop variable ($_ in this case).

Larry