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

I have three subs. Two of them are in the other sub routine. And without me calling these subs ANYWHERE in the script, they print the data inside them.

Say.

sub do_this { sub new_sub { print "test"; } sub new_sub2 { print "test2"; } }
This is untested but it's identicaly to what I'm using. Why do the two inside routines get called and actually do ANYTHING when I don't call them EVER?

Replies are listed 'Best First'.
Re: Sub routines not playing fair
by thospel (Hermit) on Oct 24, 2004 at 00:23 UTC
    They will only get activated if they get called somewhere. Really.

    I should also note that putting named subs inside another sub doesn't make much sense in perl. The names will get installed as global names in the current package anyways (at compile time even). And you will get very strange effects as soon as closures start playing a role.

    Executive summary: don't do that.

      "And you will get very strange effects as soon as closures start playing a role."

      Here is thospel's strange effects ;-)

      do_this("abc\n"); do_this("123\n"); sub do_this { my $msg = shift; new_sub(); sub new_sub { print $msg; } }

      This prints:

      abc abc
Re: Sub routines not playing fair
by TheEnigma (Pilgrim) on Oct 24, 2004 at 00:17 UTC
    Well, just the code you show there won't print anything. You'll have to include some of the rest of your code to allow us to help you. Preferably just enough to make the problem manifest itself.

    TheEnigma

Re: Sub routines not playing fair
by Joost (Canon) on Oct 24, 2004 at 00:22 UTC

      Yes, the code would help. For example, if it's this, then we can explain ;-)

      sub foo { sub BEGIN { print "BEGIN\n"; } sub INIT { print "INIT\n"; } sub END { print "END\n"; } }