Clarify and correct description of comma operator in scalar context
authorIan Goodacre <Ian.Goodacre@xtra.co.nz>
Sat, 23 Oct 2010 04:42:55 +0000 (17:42 +1300)
committerFather Chrysostomos <sprout@cpan.org>
Sat, 23 Oct 2010 06:21:39 +0000 (23:21 -0700)
The guarantee that in scalar context the comma operator evaluates its
arguments in scalar context is overstated.

In perl 5.10.0

print "Scalar assignment:\n";
$x = ( context(1), context(2), context(3) );

print "Scalar assignment in sub:\n";
sub list { ( context(1), context(2), context(3) ) }
$x = list();

sub context {

    if(wantarray) {
        print "list context\n";
    } elsif(defined(wantarray)) {
        print "scalar context\n";
    } else {
        print "void context\n";
    }
}

prints:

scalar assignment:
void context
void context
scalar context
Scalar assignment in sub:
scalar context
scalar context
scalar context

This leaves only the right argument of the last comma operator in a list as
the only one that might always be evaluated in scalar context.

The comments on the sample outputs were at best ambiguous if not misleading
or false, and also unnecessarily pejorative of perl4. The revised comments
less ambiguously refer to the last expression in the list (@y in the example)
rather than to the literal list that is the argument of the assignment
operator.

pod/perltrap.pod

index 3569709..99e25c8 100644 (file)
@@ -960,14 +960,15 @@ being required.
 =item * Comma operator in scalar context gives scalar context to args
 
 The comma operator in a scalar context is now guaranteed to give a
-scalar context to its arguments.
+scalar context to its last argument. It gives scalar or void context
+to any preceding arguments, depending on circumstances.
 
     @y= ('a','b','c');
     $x = (1, 2, @y);
     print "x = $x\n";
 
-    # Perl4 prints:  x = c   # Thinks list context interpolates list
-    # Perl5 prints:  x = 3   # Knows scalar uses length of list
+    # Perl4 prints:  x = c   # Interpolates array @y into the list
+    # Perl5 prints:  x = 3   # Evaluates array @y in scalar context
 
 =item * C<sprintf()> prototyped as C<($;@)>