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.

#! 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();
Output:
bar foo:bar baz:zap
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.

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.