title: What values should a boolean function in Perl return?
body: <p><strong>SHORT QUESTION</strong></p>
  
  <p>What are the best ways to represent true and false consistently in libraries of Perl code?</p>
  
  <ul>
  <li><p><code>1</code> / <code>0</code>?</p></li>
  <li><p><code>1</code> / the special empty string that Perl's native boolean operators<br>
  return?</p></li>
  <li><p><code>undef</code>?</p></li>
  <li><p><code>()</code> (i.e. the empty list)?</p></li>
  </ul>
  
  <p><strong>QUESTION BACKGROUND</strong></p>
  
  <p>We all know that Perl is very flexible with regard to booleans, as with most things.</p>
  
  <p>For example, Perl treats the following as false: <code>undef()</code>, the number <code>0</code> (even if written as 000 or 0.0), an empty string, <code>'0'</code> (a string containing a single 0 digit).  Perl treats the following as true: any other scalar values, <code>1</code>, <code>-1</code>, a string with a space in it (<code>' '</code>), <code>'00'</code> multiple 0s in a string, <code>"0\n"</code> (a '0' followed by a newline), <code>'true'</code>, <code>'false'</code>, <code>'undef'</code>, etc. Plus, array-to-scalar and list-to-scalar conversions mean that you can often get away with using an empty array as a false value. (Credit to <a href="http://perlmaven.com/boolean-values-in-perl" rel="nofollow noreferrer">http://perlmaven.com/boolean-values-in-perl</a> for the partial list of scalar values accepted as true or false by Perl.)</p>
  
  <p>But given all of these values that are treated as true or false, what should a Perl boolean function return?</p>
  
  <ul>
  <li><code>1/0</code></li>
  <li><code>-1/0</code> (nah)</li>
  <li><code>1/undef</code></li>
  <li><code>1/""</code></li>
  </ul>
  
  <p>If you use any of these conventions, you will quickly find that the code that you write does not behave as nicely as normal Perl code.  You will not be able to replace <code>$a&lt;$b</code>  by <code>custom_less_than($a,$b)</code> and have it work exactly the same.</p>
  
  <p>Consider:</p>
  
  <pre><code>&gt; perl -e 'use warnings; 
             sub my_eq { return ( $_[0]==$_[1] ? 1 : 0 ) }
             print "compare (1==0) &lt;&lt;".(1==0)."&gt;&gt;"
                   ." to my_eq(1,0) &lt;&lt;".my_eq(1,0)."&gt;&gt;"
                   ."\n" ;'
  Output:
  compare (1==0) &lt;&lt;&gt;&gt; to my_eq(1,0) &lt;&lt;0&gt;&gt;
  </code></pre>
  
  <p>What is the best known method for returning values from boolean functions in Perl when you are writing them yourself?</p>
  
  <p>Perhaps you want your code to be Perl-like, potentially substitutable for Perl's existing boolean operators. Or perhaps you want numeric values like 1/0. Or perhaps you come from LISP, and expect Perl's <code>undef</code> to be used LISP's <code>nil</code> for false (but then you trip upon Perl's implicit treatment of many other values as false).</p>