title: Perl: Find a sum of an array recursively with tail call optimization
body: <p>I'm trying to make a tail optimized recursive function.</p>
  
  <pre class="lang-perl prettyprint-override"><code>sub sum {
      my ($first, @rest) = @_;
  
      return @rest
          ? $first + sum(@rest)
          : $first;
  }
  
  say sum(1 .. 100);
  </code></pre>
  
  <p>It works for 100 elements however, it fails for 100_000 elements with <code>Out of memory</code> message.</p>
  
  <p>How can improve the code to make the recursion working with more elements?</p>
  
  <p><strong>Edit</strong></p>
  
  <p>Tail call optimized version of the above function:</p>
  
  <pre class="lang-perl prettyprint-override"><code>use feature qw( current_sub );
  
  sub sum_tco {
      my $loop = sub {
          my ($sum, $first, @rest) = @_;
          $sum += $first;
  
          return @rest
              ? __SUB__-&gt;($sum, @rest)
              : $sum;
      };
  
      return $loop-&gt;(@_);
  }
  </code></pre>
  
  <p>It appears that Perl 5 doesn't support TCO.</p>
  
  <p><strong>How to make TCO in Perl (if possible)?</strong></p>