in reply to Re: Re: Short circut operators in list context
in thread Short circut operators in list context

You've fallen into a trap here. This is an easy mistake even for the most adept to make.

The only difference between || and or is precedence. Brackets aka parentheses only affect context in a very few limited cases and this isn't one of them. The only effect they have here is grouping, preventing my @d = @a or @b from meaning (my @d = @a) or @b.

Here are some of the limited cases:

  • () followed by [] create a list slice, even in scalar context (where only the last element will be returned).
    @x = foo(); # foo called with list context $x = (foo()); # foo called with scalar context # note parens have no effect $x = (foo())[@foo]; # foo called with list context
  • () followed by = create a list assignment (as do @a= and %h=), placing the right of the assignment in list context.
    @x = foo(); # foo called in list context $x = (foo()); # foo called in scalar context # note parens have no effect ($x) = foo(); # foo called in list context, note lack # of parens around foo has no effect
  • lack of () around the left operand of x forces scalar context. With (), the external list or scalar context will propagate onto the left operand.
    foo() x 2; # foo called in scalar context $x = foo() x 2; # foo called in scalar context @x = foo() x 2; # foo called in scalar context (foo()) x 2; # foo called in void context $x = (foo()) x 2; # foo called in scalar context @x = (foo()) x 2; # foo called in list context

    The converse of the ()-doesn't affect context principle can be stated: functions, operators, and control constructs (and, for, etc.) create context; parentheses don't. You can look at the above list as cases where the parentheses are part of the operator; that is,  (...)[...]  ,  (...)=  , and  (...)x  are operators, and (in the case of the latter two) can apply context differently than without the parentheses.

    Updated to try not to sound so brusque, and list some of the exceptions. Updated to add examples. And converse principle. And rewrote last paragraph.