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

Are there any dangers, or extreme execution slowdown with using a subroutine inside a subroutine? Thanks for any feedback.

Replies are listed 'Best First'.
Re: sub routines inside subroutines
by chromatic (Archbishop) on Feb 27, 2001 at 09:37 UTC
    I asked a similar question about this at node Inner Subroutines, mod_perl, and Segfaults.

    The respondents gently reminded me that nested subroutines declared at compile time normally exist in the symbol table. That is, they're not made private to the enclosing subroutine.

    However, if you do nest a subroutine and refer to the enclosing scope's variables, you'll probably get a variable %s will not stay shared warning, for good reason.

    In the following code, what's the scope of $x:

    sub outer { my $x = shift; sub inner { return $x; } }
    Because you can call inner() from anywhere in the package, or anywhere you qualify it properly, it doesn't function as a closure. The proper solution in a case like this is to use a real closure:
    sub outer { my $x = shift; my $inner = sub { return $x }; }
    You'd obviously want to do more there, but that's one way to handle things properly, letting Perl worry about scoping for you.
Re: sub routines inside subroutines
by jdgamache (Novice) on Feb 27, 2001 at 20:10 UTC
    You could try an anonymous function in a function instead. ... hope it helps /JD
    use strict; main(); sub main(){ # Create a sub. my $func = sub { print "HELLO!!!\n"; }; # Call sub. &$func; }
Re: sub routines inside subroutines
by bladx (Chaplain) on Feb 27, 2001 at 09:30 UTC
    Hi there cleen! I won't say I am an expert or anything, cause I'm not, but from past experience and work I have done with subroutines within the Perl programming language, I have found that it doesn't slow a script down too much if you have a subroutine within a subroutine, but there are, however, some dangers using subroutines that I am aware of, however not fully aware of all of the possible problems.

    If i'm correct, if you use subroutines a lot, it can be fairly unsecure or at least not as secure if you just passed parameters to each other instead of using subroutines, but I am probably wrong on this point. There are many other people that can add to this telling you about the pros and cons of both... hopefully this helps :o) talk to ya later.

    bladx ~ ¡muchas veces tengo preguntas!
      It more like you will loose track of what you can and can't call if you start nesting subroutines. And when that happens, you might introduce a security hole or two.

      --
      $Stalag99{"URL"}="http://stalag99.keenspace.com";

        Which brings me to another question, is there any reason to use nested subroutines? IE a practicle use for them other then they are nested, since they dont share variables from the upper routine in which its nested from?