develooper Front page | perl.beginners | Postings from August 2009

Comma operator

Thread Next
Bryan R Harris
August 6, 2009 09:10
Comma operator
Message ID:

A question about the comma operator:

(John and Chas deserve a rest from my questions, if they want it  =).

The binary comma operator in scalar context supposedly "evaluates its left
argument, throws that value away, then evaluates its right argument and
returns that value."

So this:

  $_ = "dogs and cats";
  $r = s/o/i/g, s/s/y/g;
  print "$r: $_\n";

... prints "1: digy and caty".

Why doesn't it print a "2" instead of a "1"?  It did 2 replaces of s to y...
If I change the second line to read:

  $r = s/s/y/g;

... it prints "2: dogy and caty".  I thought given the definition above that
the comma operator should do the first replace, then do the second replace
which returns a "2", then assign that 2 to $r.  Somehow $r is getting a 1.

If instead I did:

  $r = s/o/i/g, s/s/y/g, s/d/cow/g;

... is that still a binary comma operator?  It still does all the replaces,
and still comes back with a 1.

And why is:

  print $r, "\n";

... not evaluated as a binary comma operator?  Because it's in list context?
Then why can't I do this with a list (without the parenthesis)?

  @a = 1, 2, 3;


- Bryan

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About