The following is more for the benefit gayu_justin than for kcott:

Consider what might happen if you wanted to use the $user->id version of $usr after the loop. By using my when you start the loop (as I did) you get a different variable (scoped to the loop) and avoid possible future problems.

This is an oddity, IMHO, of the way for-loop variables behave. The variable is fully localized even though it is lexical. So this code doesn't work as one (I myself, on more than one occasion) would naively expect:

>perl -wMstrict -le "my $max_x = 99; ;; for $max_x (0 .. 5) { print $max_x; last if $max_x == 2; } ;; print qq{max_x: $max_x}; " 0 1 2 max_x: 99

Nor does the loop variable do something really odd like becoming a package variable:

>perl -wMstrict -le "my $x = 'foo'; print qq{x before loop: '$x'}; ;; for $x (0 .. 2) { func(); our $y; print qq{$x, $y}; } ;; print qq{x after loop: '$x'}; sub func { our $x; our $y; $x = 99; $y = 42; } " x before loop: 'foo' 0, 42 1, 42 2, 42 x after loop: 'foo'

So what's the point of ever using a lexical loop variable in the  for my $x (...) { ... } form? If  $x was a package variable to start with, the loop variable  $x would then be fully lexically scoped. Remove the  my from the following example to see the difference.

>perl -wMstrict -le "our $max_x = 99; ;; for my $max_x (0 .. 4) { func(); print $max_x; last if $max_x == 2; } ;; print qq{max_x after loop: $max_x}; ;; sub func { $max_x = 42; } " 0 1 2 max_x after loop: 42

In reply to Re^2: showing the error ,Can't modify concatenation (.) or string in scalar assignment by AnomalousMonk
in thread showing the error ,Can't modify concatenation (.) or string in scalar assignment by gayu_justin

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.