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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.