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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Bitten by the || bug
by TimToady (Parson) on Feb 16, 2006 at 23:57 UTC | |
|
Re: Bitten by the || bug
by samtregar (Abbot) on Feb 16, 2006 at 18:00 UTC | |
|
Re: Bitten by the || bug
by brian_d_foy (Abbot) on Feb 16, 2006 at 18:25 UTC | |
|
Re: Bitten by the || bug
by Aristotle (Chancellor) on Feb 20, 2006 at 02:40 UTC | |
by tye (Sage) on Feb 20, 2006 at 16:53 UTC | |
by Aristotle (Chancellor) on Feb 21, 2006 at 01:37 UTC | |
by Aristotle (Chancellor) on Feb 20, 2006 at 18:34 UTC | |
by tye (Sage) on Feb 20, 2006 at 18:52 UTC | |
|
Re: Bitten by the || bug
by EvanCarroll (Chaplain) on Feb 19, 2006 at 03:05 UTC | |
by Tanktalus (Canon) on Feb 19, 2006 at 04:41 UTC |