my $var; for $var (...) { }

is really bad because the two instances of $var are not the same animal. The recommended code is:

for my $var (...) { }

The problem is that the first version of the code makes it look like the $var declared before the for loop is the one used in the loop and might even retain the last value it was assigned in the loop. It's not and it doesn't.

The loop variable ($var in the sample code) is an alias for each value looped over. In some sense it's not a real variable at all! To see the alias in action try:

use strict; use warnings; my @array = (1 .. 10); for my $var (@array) { $var *= 10; } print "@array";

Did you notice that the array values were altered! $var becomes each array element in turn. What you do to $var you do to the current array element.

For the vast majority of Perl code you aren't aware of this aliasing trick. Sometimes it is really useful and sometimes, if you don't know about it, it is really nasty. The same thing happens in map and grep where the default variable $_ is aliased in turn to each list element processed.

Aside from all that, don't declare multiple variables on a single line. As a general thing it's a clue that you are declaring things in the wrong place, and if it's the right place the declaration is important enough that it should be one variable per line. Along with choosing good variable names, managing variable scope (and therefore where variables are declared) are important parts of good programming style.

Perl is the programming world's equivalent of English

In reply to Re^2: Comparing two arrays by GrandFather
in thread Comparing two arrays by gilthoniel

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.