Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!jarthur!elroy.jpl.nasa.gov!jpl-devvax!lwall From: lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) Newsgroups: comp.lang.perl Subject: Re: a bug in perl3.0pl44 related to "local($_)" ? Message-ID: <11310@jpl-devvax.JPL.NASA.GOV> Date: 5 Feb 91 18:01:19 GMT References: Reply-To: lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) Distribution: comp Organization: Jet Propulsion Laboratory, Pasadena, CA Lines: 61 In article 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