in reply to Perplexing perl problem

I was really perlplexed by this one:
print (2 + 2) * 5;
prints "4". Huh?


holli, /regexed monk/

Replies are listed 'Best First'.
Re^2: Perplexing perl problem
by rev_1318 (Chaplain) on Jun 24, 2005 at 14:51 UTC
    Sure it does. the parentheses around 2 + 2 make print behave as a function, so the statement parses as:

    "print the result of 2 + 2 (4) and multiply the result of print (1) times 5. That last result is discarded, because it is is void context. You can see how is is parsed:

    perl -MO=Deparse -e 'print (2 + 2) * 5' print(4) * 5; -e syntax OK

    Paul

Re^2: Perplexing perl problem
by talexb (Chancellor) on Jun 24, 2005 at 14:53 UTC
    DB<1> print (2+2)*5; 4 DB<2> print ((2+2)*5); 20 DB<3> print 3*5; 15 DB<4> $foo=(2+2)*5; DB<5> x $foo 0 20

    Well, I guess it's some side effect to do with print.

    Alex / talexb / Toronto

    "Groklaw is the open-source mentality applied to legal research" ~ Linus Torvalds

      Shame the debugger doesn't honour -w

      P:\test>perl -wde1 perldb: Must not source insecure rcfile ./perldb.ini. You or the superuser must be the owner, and it must not be writable by anyone but its owner. Loading DB routines from perl5db.pl version 1.25 Editor support available. Enter h or `h h' for help, or `perldoc perldebug' for more help. main::(-e:1): 1 DB<1> print (2+2)*5;; 4 DB<2> q P:\test>perl -wle"print (2+2)*5" print (...) interpreted as function at -e line 1. Useless use of multiplication (*) in void context at -e line 1. 4

      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
      "Science is about questioning the status quo. Questioning authority".
      The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.