You aren't the first to be bitten by this and you won't be the last. This is enough of a "gotcha" that it gets own discussion in perlvar. Because $_ gets assigned the current value foreach loops and functions like grep and map, it is easy to think that each code block gets its own value of $_.
However, $_ is a global variable and it only gets its own value inside a code block if you localize it. The for/foreach loop and functions like grep and map do this implicitly. Any subroutine you write has to do this explicitly, like this:
sub func { local $_; # THIS IS THE KEY LINE YOU NEEDED open(READ, "< test.txt"); while(<READ>) { # print; } close READ; return; } # outputs the final line w/o a problem Files: ree ree1 ree2 $VAR1 = [ 'ree', 'ree1', 'ree2' ]; The file is ree The file is ree1 The file is ree2 Files: ree ree1 ree2
The behavior of $_ can be confusing, but one *nice* thing about it is that you can use it to create your very own special funky map and grep routines. Here is an example of a small routine that lets you do custom processing on every other list member:
use strict; use warnings; sub forEveryOther(&@) { my @aData = @_[1..$#_]; my @aResults; local $_; for (my $i=0; $i < $#aData; $i+=2) { $_ = $aData[$i]; push @aResults, $_[0]->(); } return @aResults; }
which we can use like this
my @people = (bob => 53, peter => 200); my @hello = forEveryOther { "Hello, $_\n" } @people; print @hello; # outputs Hello, bob Hello, peter
Best, beth
In reply to Re: Array element getting deleted
by ELISHEVA
in thread Array element getting deleted
by vinoth.ree
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |