On Mon, Jan 25, 2016 at 12:24:04AM +0100, lee wrote: > Paul Johnson <p...@pjcj.net> writes: > > > On Sun, Jan 24, 2016 at 05:44:14PM +0200, Shlomi Fish wrote: > >> Hi lee, > >> > >> On Sun, 24 Jan 2016 13:11:37 +0100 > >> lee <l...@yagibdah.de> wrote: > >> > >> > Paul Johnson <p...@pjcj.net> writes: > >> > > > >> > > In scalar context the comma operator evaluates its left-hand side, > >> > > throws it away and returns the right-hand side. > >> > > >> > What is the useful use for this operator? > >> > > >> > >> Well, I believe its use was originally inherited from > >> https://en.wikipedia.org/wiki/C_%28programming_language%29 where one can do > >> something like: > >> > >> x = (y++, y+2); > >> > >> In Perl 5 though it is preferable to use do { ... } instead: > >> > >> $x = do { $y++; $y+2; }; > > > > In both Perl and C the comma operator is probably most usually > > (deliberately) > > seen in for statements: > > > > #!/usr/bin/env perl > > > > use strict; > > use warnings; > > > > for (my ($x, $y) = (1, 7); $x < 5; $x++, $y--) { > > print "$x $y\n"; > > } > > > > and > > > > #include <stdio.h> > > > > int main() { > > int x, y; > > for (x = 1, y = 7; x < 5; x++, y--) > > printf("%d %d\n", x, y); > > return 0; > > } > > > > both of which produce the output: > > > > 1 7 > > 2 6 > > 3 5 > > 4 4 > > Ok and how is the comma operator usefully useful?
Beyond what I have written above, I have had little use for it in C and less in Perl. But I have no doubt that were you to ask in the appropriate forum then someone could provide a compelling argument. > Obviously, I could > use it to create convoluted code, which is usually not my intention. > > Consider with these examples that an expression like (1, 3) might > unexpectedly evaluate to 3, and you start to think that you don't like > things like > > > sub s { > my $a = 1; > my $b = 3; > > return ($a, $b); > } > > > anymore because you could, by mistake (or intentionally), write > > > my $x = s; > > > . So let me re-phrase my original question to: How do you /safely/ > return arrays? > > That means I need an error message for '$x = s;' because I'd write that > only by mistake. You could add to your subroutine: die "Only call in list context" unless wantarray; -- Paul Johnson - p...@pjcj.net http://www.pjcj.net -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/