xiaoyafeng has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks,

perl -e "$c=qq(c);$d=qq(d); $c = $d++; $d = $c++; print $c,$d;" + # output: ed
any thoughts?




I am trying to improve my English skills, if you see a mistake please feel free to reply or /msg me a correction

Replies are listed 'Best First'.
Re: letters++, bug or trick?
by BrowserUk (Patriarch) on Jan 30, 2010 at 07:21 UTC

    It's all perfectly logical really. The first thing to notice is that the initialisation of $c makes no difference to the outcome:

    perl -e "$c=qq(z);$d=qq(d); $c = $d++; $d = $c++; print $c,$d;" ed perl -e "$d=qq(d); $c = $d++; $d = $c++; print $c,$d;" ed

    So,

    1. $d is set to 'd'
    2. $c is set to $d ('d')
    3. $d is incremented ('e')
    4. $d is set to $c ('d')
    5. $c is incremented ('e')
    6. 'ed' is printed.

    In the end, the whole thing reduces to:

    perl -e "$d=qq(d); $c = $d; $d = $c++; print $c,$d;" ed

    or even just

    perl -e "$c = $d = qq(d); $c++; print $c,$d;" ed

    Which looks a lot less mysterious :)


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      Ah! too much ++ confused me! the last statment is really a concise answer! thanks!




      I am trying to improve my English skills, if you see a mistake please feel free to reply or /msg me a correction

Re: letters++, bug or trick?
by biohisham (Priest) on Jan 30, 2010 at 08:12 UTC
    This is not a bug nor a trick neither, the ++ operator works on strings stored in scalar variables as long as they have never been used in a numeric context, once these variables are used in a numeric context a re-initialization of the variable's value into a number takes place..
    #!/usr/local/bin/perl $c = "c"; print ++$c," from c\n"; print ++$c," from d\n"; #apply the same in numeric context $c+=0; print $c, " from numeric operation\n"; print ++$c, " incremented after numeric assignment";
    However, Perl would throw a warning when it reaches to "$c+=0;" telling you that a non-numeric argument is used in the addition operation if you have turned warnings on via "use warnings" which can save you from introducing a potentially hard-to-track bug otherwise...


    Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind.