I have two snippets of code and I was wondering why they produced different results (P is like printf w/auto LF).

> perl -E ' use P; for ($_=3;$_-- >0;) { P "_=%s", $_ }' _=2 _=1 _=0
> perl -E ' use P; P "_=%s", $_ for $_=3;$_-- >0; ' _=3

Note, I didn't say "for my $i...". That would make sense. But the behavior seems like that's what it did. However, a similar construct the reversed "if", doesn't act this way:

> perl -E ' use P; $_=1; P "_=$_" if --$_; > P "got to end w/_=%s", $_; > ' got to end w/_=0 #alternatively: > perl -E ' use P; $_=12; P "_=$_" if --$_; P "got to end w/_=%s", $_; ' _=11 got to end w/_=11

This is in perl 5.16.1. Could someone explain why these look inconsistent to me? (i.e. "$_" value in the conditional statement isn't consistent with it's value in the test or outside the loop.

Thanks!
Curious one.

---
FWIW -- the postfix 'while' seems to be consistent, giving the same results in regular vs. postfix form;

In reply to Why/how are these different? by perl-diddler

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.