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

Hello all, I was wondering how would I go about making a function local to another function in PERL?

Replies are listed 'Best First'.
(tye)Re: Functions
by tye (Sage) on Jan 30, 2001 at 01:09 UTC
    { my $sub; BEGIN { $sub= sub { # ... }; } sub GlobalRoutine { &$sub( ... ); } }

    Is one way to do it.

            - tye (but my friends call me "Tye")
      You shouldn't need the BEGIN block in there. The $sub var will go out of scope at the end of the block anyways. Nice closure of a subroutine.

      Cheers,
      KM

        exit main( @ARGV ); { my $sub; BEGIN { $sub= sub { # ... }; } sub GlobalRoutine { &$sub( ... ); } } sub main { # ... }

        It is easy to put this in places where the BEGIN block becomes necessary. Some are much more subtle than this. Without the BEGIN block, $sub is declared and GlobalRoutine is compiled before $sub is initialized so it then becomes possible for GlobalRoutine to be called while $sub is still undef.

        I'm sorry that Perl doesn't have real static variables such that I have to resort to an extra empty block and doing the initialization in a BEGIN block. Note that this trick won't work if you are using mod_perl.

        FYI, since I didn't use any local variables in the anonymous subroutine, it isn't a closure in my book.

                - tye (but my friends call me "Tye")
Re: Functions
by KM (Priest) on Jan 30, 2001 at 01:06 UTC
    You want a closure on a function? Or something else?

    Cheers,
    KM