in reply to The behavior when assigning an array to scalar?

An alternate way of looking at the problem (besides focusing on the comma's behavior as an operator): is that in the 2nd example, you are putting parentheses around a list. You'll get the same value assigned to "$s" whether you use parentheses or not.

In a way, it's similar to using semi-colons to separate statements that are grouped together:

my $s = do {"111"; "222"; "aaa"; "bbb"}; print $s."\n";
The above also prints "bbb" -- but if you have warnings on, it will also warn you that the first 3 items are ignored:
> perl -e ' use warnings; my $s = do {"111"; "222"; "aaa"; "bbb"}; print $s."\n";' Useless use of a constant ("111") in void context at -e line 3. Useless use of a constant ("222") in void context at -e line 3. Useless use of a constant ("aaa") in void context at -e line 3. bbb

Replies are listed 'Best First'.
Re^2: The behavior when assigning an array to scalar?
by haukex (Archbishop) on Sep 27, 2017 at 08:10 UTC
    You'll get the same value assigned to "$s" whether you use parentheses or not.

    Sorry, but that's not correct, as choroba showed in his update shortly after posting. The reason is that assignment has slightly higher precedence than the comma.

    $ perl -le 'my $s = ("111","bbb"); print $s' bbb $ perl -le 'my $s = "111","bbb" ; print $s' 111 $ perl -MO=Deparse,-p -e 'my $s = ("111","bbb")' (my $s = ('???', 'bbb')); $ perl -MO=Deparse,-p -e 'my $s = "111","bbb" ' ((my $s = '111'), '???');
    it will also warn you that the first 3 items are ignored

    You get those warnings with commas as well - but it's a good point, since it hints that the OP may not be using warnings. fgg1991: Always Use strict and warnings!

    $ perl -wMstrict -e 'my $s = ("111","222","aaa","bbb")' Useless use of a constant ("111") in void context at -e line 1. Useless use of a constant ("222") in void context at -e line 1. Useless use of a constant ("aaa") in void context at -e line 1. $ perl -wMstrict -e 'my $s = "111","222","aaa","bbb" ' Useless use of a constant ("222") in void context at -e line 1. Useless use of a constant ("aaa") in void context at -e line 1. Useless use of a constant ("bbb") in void context at -e line 1.
      Re: precedence... wow.. so perl is different than C in that case? Thought for sure C took the right most element and that perl was designed to follow C precedence rules. hmmm...I should probably go test a C case now...
        C doesn't have context, but the behaviour of comma is very similar to Perl:
        #include <stdio.h> int main () { int i; i=1,2,3; printf("%d\n", i); i=(1,2,3); printf("%d\n", i); return 0; }

        Update: more similar example chosen.

        ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,