in reply to Precendence and wantarray puzzling me

my @thingies = foo() or bar(); warn @thingies; # Expected (3,4) here, got (1)
You got (1)? That would be a bug. I get an empty list, as I expect. foo() returns an empty list, which is assigned to @thingies. bar() is called, but its result is discarded.
my @thingies = ( foo() ) or ( bar() ); warn @thingies; # Expected (3,4) here too, got ()
And rightly so. This is exactly the same expression as the first one. The parens are for precedence only, and a fairly trivial one.
however, with or, why doesn't the first sub get called in list context, return false with the empty list, and let the second sub get called?
But this is exactly what is happening! Perhaps you don't realize the difference between or and ||: precedence. or has a low precedence, lower than assignment. Perhaps you want:
my @thingies = foo (); @thingies = bar () unless @thingies;

Abigail

Replies are listed 'Best First'.
Re: Re: Precendence and wantarray puzzling me
by BUU (Prior) on Mar 04, 2004 at 20:59 UTC
    my @thingies = foo (); @thingies = bar () unless @thingies;
    When I first saw that, I thought to myself "Couldn't that unless @thingies modifer be replaced by an ||=?" So I tried it, perl -e"@x=qw/foo bar/; @x ||= qw/baz/; print @x" And got this lovely error: Can't modify array dereference in logical or assignment (||=) at -e line 1, near "qw/baz/;". Can anyone explain why ||= doesn't work with an array, and what that error means?
      EXPR1 ||= EXPR2 is sort of a super charged EXPR1 = EXPR1 || EXPR2. However, if EXPR1 is an array (say @a), it would expand to: @a = @a || EXPR2. Nothing wrong with the latter, but the two @a's are quite different. The one on the left hand side is an lvalue in list context, the one on right hand side of the assignment is in scalar context. However, EXPR1 ||= EXPR2 isn't syntactic sugar for EXPR1 = EXPR1 || EXPR2, because in the latter, EXPR1 is executed twice, in the former, just once. But if EXPR1 in EXPR1 ||= EXPR2 is only going to be executed once, what should it be? The scalar value, or the list value? Both are needed.

      Abigail