Path: utzoo!attcan!uunet!samsung!usc!elroy.jpl.nasa.gov!jpl-devvax!lwall From: lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) Newsgroups: comp.lang.perl Subject: Re: Bug -- variable corruption inside sub/foreach Message-ID: <7018@jpl-devvax.JPL.NASA.GOV> Date: 8 Feb 90 05:57:00 GMT References: <4080010@hpausla.aso.hp.com> Reply-To: lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) Organization: Jet Propulsion Laboratory, Pasadena, CA Lines: 32 In article <4080010@hpausla.aso.hp.com> brian@hpausla.aso.hp.com (Brian Coogan) writes: : I seem to have managed to find another bug in perl. A variable $file is : corrupted by reading from a filehandle (variable name doesn't seem : to matter, nor does it matter whether $file is local or not, or the : first/most recent variable use beforehand.) I've worked around this : bug, but it lost me a lot of time. The variable gets corrupted to : the value of $_. Oddly enough, it's not really a perl bug in this case. What you've got is do checkfiles($_); sub checkfiles { foreach $file (@_) { while () { ... } } } What you have to remember is that @_ is an array of references to the actual parameters (not copies, as in 2.0), and that foreach iterates over an array by making the variable ($file, in this case) to be a reference to the actual array elements. Hence, when checkfiles is called with $_, it ends up aliased to $file. So reading into $_ then clobbers $file too. That's the fun of passing parameters by reference. I still think it's worth it for the efficiency gain. If it worries you, just be consistent about copying your parameters out of @_ into something local. Or tell yourself to worry about aliasing whenever you don't. Or something like that. Larry