in reply to Array element getting deleted

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

Replies are listed 'Best First'.
Re^2: Array element getting deleted
by ack (Deacon) on Apr 17, 2009 at 18:13 UTC

    ELISHEVA (and other repliers) are offering great advice and council. In addition to the variety of suggestions offered, they also point out one real root, from my perspective, of the problem the OP is facing...i.e., $_ is a global variable. So the subroutine ends up overwriting it.

    This is a clasic example of where the Perl gurus advise that it is important (and the only way for special variables like $_) to use the 'local' function to keep from overwriting it in the subroutine.

    ack Albuquerque, NM