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

Hi Monks,

inspired by strats little 'regards-obscu' i played a little with the comma-operator.

I found this strange behavior

# perl -e 'print "one\n",print "two\n"' two one 1
Okay, i'm thinking the '1' represents the successful processing of the second print which will be printed after the 'one'. The printing of 'two' at first seems to be dealing with the fact that the lefts of comma-separated values are thrown away and only the rightmost is returned.

When i tried another example i became really confused.

# perl -we 'print $a=3,"\n",print $a-5,"\n"' -2 3 1
Why does the second print already know the value of $a, if the working direction is reverse ?

Replies are listed 'Best First'.
Re: comma-operator quirks
by BrowserUk (Patriarch) on Jun 14, 2003 at 17:23 UTC

    My interpretation.

    Perl interprets lists, including function parameter lists, left to right.
    It first evaluates $a=3 & "\n", then it attempts to evaluate the third argument, which is the second print.
    So now it has to evaluate it's parameters ($a-5 & "\n") and gets (-2, chr(10)) and passes these to print.
    print outputs them, and returns true (1).

    It now has the values of the arguments to the first print (3,chr(10),1), so it passes them.
    print outputs these and returns true to a void context.

    And perls interpretation

    perl58 -MO=Deparse,-p -e"print $a=3, $/, print $a-5, $/" print(($a = 3), $/, print(($a - 5), $/)); -e syntax OK

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller


Re: comma-operator quirks
by TomDLux (Vicar) on Jun 14, 2003 at 16:57 UTC

    You have one print statement, which takes two arguments, the first is the result of $a=3 and the second is the result of print $a-5.

    To evaluate the two prints, the arguments need to be procecessed before the function is invokved. If you have a function with several arguments:

    print $a+3, $b-2;

    The order in which arguments are prepared is arbitrary. Programming languages generalll have some limits on how much you can vary a variable within a single range, say within a single statement.

    Although you have two sub-statements, Perl apparently performs all the pre-processing before either print is invoked. But it could just as easily be implemented so that $a-5 is evaluated before $a=3.

    --
    TTTATCGGTCGTTATATAGATGTTTGCA