Grep aliases the current value of $_ to the original array element, and thus modifying it actually tampers our original data

That's true, and good to point out. But it's also good to point out that for does the same thing. And the solution with grep is the same -- copy the values before modifying them. Which, incidentally, is exactly what my example snippet does. It copies the values into a new array. If you plug my example in just as I wrote it, the problem goes away:

my $line = "Alpha and some beta junk here"; my @keywords = qw(alpha beta gamma); my @found = grep { $line =~ /$_/i } @keywords; foreach (@found) { $_ = rand; } print "@keywords\n"; __OUTPUT__ alpha beta gamma

So, while the gotcha didn't affect my example directly, I'm glad you brought it up. Anyone who wasn't aware of it will likely benefit from this discussion.


In reply to Re^6: Missing $ on loop variable by revdiablo
in thread Missing $ on loop variable by superfrink

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.