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

-- 
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/


Reply via email to