title: How to implement assert in Perl?
body: <p>When trying to implement C's <code>assert()</code> macro in Perl, there is some fundamental problem. Consider this code first:</p>
  
  <pre><code>sub assert($$) {
     my ($assertion, $failure_msg) = @_;
     die $failure_msg unless $assertion;
  }
  
  # ...
  assert($boolean, $message);
  </code></pre>
  
  <p>While this works, it's not like C: In C I'd write <code>assert($foo &lt;= $bar)</code>, but with this implementation I'd have to write <code>assert($foo &lt;= $bar, '$foo &lt;= $bar')</code>, i.e. <em>repeat</em> the condition as string.</p>
  
  <p>Now  I wonder how to implement this <em>efficiently</em>. The easy variant seems to pass the string to <code>assert()</code> and use <code>eval</code> to evaluate the string, but you can't access the variables when evaluating eval. Even if it would work, it would be quite inefficient as the condition is parsed and evaluated each time.</p>
  
  <p>When passing the expression, I have no idea how to make a string from it, especially as it's evaluated already.</p>
  
  <p>Another variant using <code>assert(sub { $condition })</code> where it's likely easier to make a string from the code ref, is considered too ugly.</p>
  
  <p>The construct <code>assert(sub { (eval $_[0], $_[0]) }-&gt;("condition"));</code> with</p>
  
  <pre><code>sub assert($)
  {
      die "Assertion failed: $_[1]\n" unless $_[0];
  }
  </code></pre>
  
  <p>would do, but is ugly to call.
  The <em>solution</em> I am looking for is to <em>write the condition to check <strong>only once</em></strong>, while being able to <strong>reproduce the original (non-evaluated) condition</strong> and <strong>efficiently evaluate the condition</strong>.</p>
  
  <p>So what are more elegant solutions? Obviously solutions would be easier if Perl had a macro or comparable syntax mechanism that allows transforming the input before compiling or evaluating.</p>