On 04/03/2012 10:21, Manfred Lotz wrote:

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.

$_ is a package variable. You can fully-qualify it here and access it
as $main::_.

Perl itself takes care of using $_ in foreach loops by localizing it
within every such loop. The problem is usually when it is implicitly
used in a while loop, as here. If you use a named variable in read loops
then you should be safe.

Rob

--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/


Reply via email to