http://qs321.pair.com?node_id=11109019

likbez has asked for the wisdom of the Perl Monks concerning the following question:

Esteemed monks,

What is the best way to escape from multilevel, deeply nested calls to the main program (say with the call nesting level close to a hundred) that resulted in error somewhere close the most deep nesting level (unwinding of failed calls).

Can I use exceptions mechanism for this to jump immediately to the main program? If yes, how?

For example, in the example below (for demonstration purposes only) we need to exit from all levels if we detect a loop in recursion calls. And the required code is rather ugly and inefficient: checks need to be made both on entry and after each subroutine call in each module.

use v5.10; use warnings; use strict 'subs'; use feature 'state'; $global_failure=0; $rc=d('d'); say "\nProgram ended"; say "Failure_code is $global_failure"; exit $rc; sub d { state $recursion_level=0; $recursion_level++; if ($recursion_level>10){ $global_failure++; return $recursion_level; } print $_[0].$recursion_level; $rc=e('e'); if( $rc ){ $global_failure++; $global_failure++; print '-'.$_[0].$recursion_level; $recursion_level--; return $recursion_level; } $recursion_level--; return 0; } sub e { state $recursion_level=0; $recursion_level++; if ($recursion_level>10){ $global_failure++; print '-'.$_[0].$recursion_level; $recursion_level--; return $recursion_level; } print $_[0].$recursion_level; $rc=f('f'); if ($rc) { $global_failure++; print '-'.$_[0].$recursion_level; $recursion_level--; return $rc; } $recursion_level--; return 0; } sub f { state $recursion_level=0; $recursion_level++; if ($recursion_level>10){ $global_failure++; print '-'.$_[0].$recursion_level; $recursion_level--; return $recursion_level; } print $_[0].$recursion_level; $rc=f('f'); if ($rc) { $global_failure++; $recursion_level--; print '-'.$_[0].$recursion_level; return $rc; } $recursion_level--; return 0; }
... ... ...