in reply to Re: ternary operator as lvalue failing to induce evaluation of right-hand expression in list context
in thread ternary operator as lvalue failing to induce evaluation of right-hand expression in list context
Deparse shows that the parentheses in the OP are unnecessary, which is as expected, since the conditional operator ?: has a higher precedence than assignment (see Operator Precedence and Associativity). Consider:
#! perl use strict; use warnings; my @x = qw(Initial list of words 1); my $y = 'Initial string 1'; show('With parentheses'); my @z = ( time() ? @x = qw(Words_z from conditional) : $y ) = foo(); print "\@z = (@z)\n"; show('After assignment to LHS'); @x = qw(Initial list of words 2); $y = 'Initial string 2'; show('Without parentheses'); my @w = time() ? @x = qw(Words_w from conditional) : $y = foo(); print "\@w = (@w)\n"; show('After assignment to LHS'); sub foo { if (wantarray()) { print "\nfoo called in list context\n"; return qw(sub_foo word list); } else { print "\nfoo called in scalar context\n"; return 'String_from_foo'; } } sub show { my ($heading) = @_; print "\n$heading:\n\n"; print "\@x = (@x)\n"; print "\$y = '$y'\n"; }
Output:
17:35 >perl 678_SoPW.pl With parentheses: @x = (Initial list of words 1) $y = 'Initial string 1' foo called in scalar context @z = (String_from_foo) After assignment to LHS: @x = (Words_z from conditional) $y = 'Initial string 1' Without parentheses: @x = (Initial list of words 2) $y = 'Initial string 2' foo called in scalar context @w = (String_from_foo) After assignment to LHS: @x = (Words_w from conditional) $y = 'Initial string 2' 17:35 >perl -v This is perl 5, version 18, subversion 0 (v5.18.0) built for MSWin32-x +86-multi-thread-64int
It’s clear that foo is being evaluated in scalar context, even though the condition evaluates to true and so chooses the LHS. Since foo would still be evaluated in scalar context if the condition were false and the RHS chosen, it’s now clear why the compile error has disappeared: it is known at compile time that foo will be evaluated in scalar context.
But that leaves us with some unanswered questions:
I have the feeling that there’s an obvious answer to all this, but I can’t see it. Which is, just possibly, related to the fact that in my neck of the woods the Ashes coverage finishes around 3:30 am... |-O
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: ternary operator as lvalue failing to induce evaluation of right-hand expression in list context
by choroba (Cardinal) on Aug 05, 2013 at 09:36 UTC | |
by Anonymous Monk on Aug 05, 2013 at 10:42 UTC | |
by ed_hoch (Sexton) on Aug 05, 2013 at 17:54 UTC |