Why is Perl so afraid of “deep recursion”?

后端 未结 4 1164

I recently stumbled across the book Higher-order Perl, which basically suggests ways to do things in Perl in a functional way. The author explains that Perl has 6 o

4条回答
  •  -上瘾入骨i
    2021-01-07 17:09

    The “deep recursion” warning is optional, and an indicator that something may have gone wrong: most of the time, a function calling itself over and over again isn't intended (Perl is a multi-paradigm language, and many people don't use functional idioms). And even when consciously employing recursion, it is far too easy to forget the base case.

    It's easy to switch the “deep recursion” warning off:

    use warnings;
    no warnings 'recursion';
    
    sub recurse {
      my $n = shift;
      if ($n) {
        recurse($n - 1);
      }
      else {
        print "look, no warnings\n";
      }
    }
    
    recurse(200);
    

    Output:

    look, no warnings
    

    It is true that Perl does not perform tail recursion optimization, because that would mess up the caller output (which is vital for some things like pragmas or Carp). If you want to manually perform a tail call, then

    return foo(@args);
    

    becomes

    @_ = @args; # or something like `*_ = \@args`
    goto &foo;
    

    although bad things can happen if you foolishly localized @_.

提交回复
热议问题