Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re^2: The behavior when assigning an array to scalar?

by haukex (Archbishop)
on Sep 27, 2017 at 08:10 UTC ( [id://1200172]=note: print w/replies, xml ) Need Help??


in reply to Re: The behavior when assigning an array to scalar?
in thread The behavior when assigning an array to scalar?

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.

Replies are listed 'Best First'.
Re^3: The behavior when assigning an array to scalar?
by perl-diddler (Chaplain) on Sep 27, 2017 at 14:59 UTC
    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,

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1200172]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (2)
As of 2024-04-26 02:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found