I just learned, the hard way, that || doesn't do what I mean in list context. I'm sure it's in the documentation that I read years ago. But I've forgotten.
I commonly use $scalar || $other_scalar. Nearly as common is scalar_func() || other_scalar_func(). What I just tried, and was surprised that it didn't work, was list_func() || other_list_func().
What I meant was "if list_func() returns an empty list, call other_list_func() and use its list, otherwise use list_func's list return." What perl thought I meant was something completely different.
Output:#! perl -l use strict; use warnings; sub list0 { qw() } sub list1 { qw(foo bar); } sub list2 { qw(baz zap) } sub do_it { list1() || list2(); } sub do_it_right { my @x = list1(); @x = list2() unless @x; @x; } sub do_it2 { list0() || list2(); } print join ':', do_it(); print join ':', do_it_right(); print join ':', do_it2();
My original code was much more complex - and I'm not even sure how, when it was like do_it, it actually came back with "1" instead of "bar". But it did.bar foo:bar baz:zap
Remember, folks: || gives you a scalar context on the left side of the operator. Just like it says in perlop under "C-style Logical Or". <sigh>
I wonder if perl6 will gives us a bit more syntactical sugar for this ;-)PS: for those who haven't seen this English idiom, the title doesn't mean || has a bug. It means that I've grown addicted to using it. Sort of like "bitten by the gambling bug" means that one is gambling a lot.
In reply to Bitten by the || bug by Tanktalus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |