Now, your post seems a little ambiguous (to my eyes), but if you are looking for a shorter way to directly modify array elements (not copies), then:

my @array = (1,2,3); $_ *= 2 for @array; print "@array\n"; # prints: 2 4 6

This works because the loop variable is aliased to each lvalue in the list in turn. This also means that such code will throw an exception if any of the elements in the list are not lvalues and you try to modify them:

$_ *= 2 for 1,2,3; # error: modification of read-only value

Now, if you actually meant you want to muck about without changing the actual array itself, then copying the loop variable inside the loop is one easy way. Another possibility is to generate the list via map():

my @array = (1,2,3); for my $e (map $_, @array) { $e++; # or whatever } print "@array\n";

However, this builds a new list and iterates over it, so it would be more efficient (memory-wise) to just make a copy of each item inside the loop as you did (at least for largish arrays).


In reply to Re: Modify array elements inside for loops by danger
in thread Modify array elements inside for loops by sguazt

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.