Hi Rob, Thanks for your reply. On Sun, 04 Mar 2012 09:50:07 +0000 Rob Dixon <rob.di...@gmx.com> wrote:
> On 04/03/2012 07:56, Manfred Lotz wrote: ... > > > > Running this gives: > > > > Sub3: Issuing [uname -a] > > Linux hogwart 3.0.0-14-generic-pae #23~lucid1-Ubuntu SMP Thu Dec 8 > > 15:03:12 UTC 2011 i686 GNU/Linux 0 > > Sub3: Issuing [date] > > Sun Mar 4 08:54:18 CET 2012 > > 0 > > Use of uninitialized value $cmd in concatenation (.) or string > > at ./foreach1.pl line 20. > > > > Sub1 > > 1 > > Use of uninitialized value $cmd in concatenation (.) or string > > at ./foreach1.pl line 20. > > > > Sub1 > > 1 > > > > > > What am I doing wrong here? > > Hi Manfred > > You have discovered why many people say it is unsafe to use $_. $_ is > a global variable, and the loop > > while (<$fh> ) { print; } > > modifies it, leaving it undefined at end of file. Unfortunately the > loop > > foreach ( @cmds ) { say sub1($_); }; > > has aliased $_ to each of the elements of @cmds, so the array is > getting corrupted by the subroutine call. > Yep, I thought that $_ is somewhow a globally available lexical variable. > You can get around this either by using a named variable for reading > from the pipe, or by adding > > local $_; > I would prefer then to not use $_ in the foreach loop but doing as Tim suggested. foreach my $v (@cmds) { somesub($v); }; My conclusion is now that only in really simple cases it is safe to use $_ in a foreach loop. Thanks again to you and Tim. -- Manfred -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/