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

C:\strawberry\perl\bin\samples>perl print(print (5+2)+10) ^Z 711

why it results 711 ?

Replies are listed 'Best First'.
Re: logic behind the print function
by ikegami (Patriarch) on Dec 29, 2009 at 14:59 UTC

    You should have turned on warnings, especially when things didn't work as you expected them to.

    $ perl -wle'print(print (5+2)+10)' print (...) interpreted as function at -e line 1. 7 11

    That message means the space between print and the paren isn't significant.

    print(5+2) prints 7 and returns a true value (which happens to be 1) on success.

    print(1+10) prints 11.

    Maybe you want

    print( (5+2)+10 )

    Omitting parens around the args of Perl function calls is perilous.

Re: logic behind the print function
by Corion (Patriarch) on Dec 29, 2009 at 14:59 UTC

    What did you expect?

    Perl evaluates the arguments to all calls to print from leftmost-innermost to right. So it first prints the 7, then prints the result from the print function +10.

Re: logic behind the print function
by masak (Scribe) on Dec 29, 2009 at 16:18 UTC

    The original poster is, it seems, confused by two things: first, that the result of a (successful) print is 1, and not the thing printed. Second, that the parentheses around (5+2) delimit the arguments sent to the inner 'print' call. Both of these are obvious to more seasoned Perl programmers, but not to newbies.

    It is my irreverent but humble duty to report that Perl 6 'fixes' the second of these points of confusion, by having print(5+2) and print (5+2) (note the space) mean different things. In the first instance, (5+2) is parsed as an argument list with one argument, 5+2. In the second instance, because of the space after print, the parser expects a non-parenthesized list of arguments, and finds (5+2)+10.

    So, a Perl 6 inplementation prints "171": "17" for the correct result of the calculation (5+2)+10, and "1" for the outer print of the return value of the inner print.

      Oh, and users of both Perl 5.10 and Perl 6 would likely have instinctively used say rather than print to begin with; say is shorter to write, and gives you an extra newline for free, making the output easier to parse for human eyes.
Re: logic behind the print function
by Fletch (Bishop) on Dec 29, 2009 at 15:38 UTC

    One thing that may be germane depending on what other language(s) you're familiar with: print, like most (all? trying to think of an exception because I'm sure if I say all someone will follow up with the one I miss :) builtins in perl, is a function and has a return value. If you're used to (the only immediate examples coming to mind would be Ada or Pascal) some other language that makes a distinction between functions which have return values and procedures which do not this might seem strange.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.