Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can set a hard maximum recursion depth in Perl?

Tags:

recursion

perl

Although in some cases I might want to allow deep recursions in my code, I want to be able to disable it in certain cases (like while testing).

I know that when using the debugger I can use $DB::deep to specify the maximum recursion depth, and the feature I'm after is basically the same but usable even when not in the debugger.

I took a look in CPAN, but I couldn't find anything. And a search on PerlMonks lead me to a thread about changing the behaviour of the deep recursion warning. What I'm after is a to be able to block recursions altogether (eg. die if the recursion gets too deep).

Does this feature exist?

Bonus points if the solution allows me to localise it, so that I can control the scope of a maximum recursion depth.

like image 581
jja Avatar asked Aug 24 '18 11:08

jja


2 Answers

As a previous answer mentions, you can only change the level that triggers the warning, by recompiling Perl.

But you can make the existing warning fatal like this:

use warnings FATAL => 'recursion';
like image 151
Dave Cross Avatar answered Sep 22 '22 08:09

Dave Cross


According to perldoc perldiag:

Deep recursion on subroutine "%s" (W recursion)
This subroutine has called itself (directly or indirectly) 100 times more than it has returned. This probably indicates an infinite recursion, unless you're writing strange benchmark programs, in which case it indicates something else.

This threshold can be changed from 100, by recompiling the perl binary, setting the C pre-processor macro PERL_SUB_DEPTH_WARN to the desired value.

So it seems you cannot localize the behavior unless you modify the perl binary.

like image 40
Håkon Hægland Avatar answered Sep 24 '22 08:09

Håkon Hægland