in reply to dynamic sub routine definitions?

Ah, a wheel waiting to be re-invented. ;-)

The do function will do exactly what you describe: read in a file, compile it as Perl, and execute it. It's been around a while, and there are many better alternatives, such as require and use. For more information on the latter two, look at perlmod.

However, being able to load and run a file will not make your program dynamic. You can't use stuff like this to replace an existing function definition, only to add a new one. What you want can be done, but requires more work: you need a level of indirection, so you can change the definition but keep the name. Possible, but difficult and very error-prone. Do you have a specific use in mind? (Other than "neat!" -- a valid reason, mind you.)

Replies are listed 'Best First'.
Re: Re: dynamic sub routine definitions?
by Eradicatore (Monk) on Jul 17, 2002 at 02:55 UTC
    Thank you both! Yes, this is actually what I want to do. I don't want to redefine a function. Just have a function that I can update and have those changes automatically show up by people running the app. So for me to change the programs behaviour a bit, I can just update this text file, and when the program is started, it checks for a newer version of this file. If there is one, it downloads it and then I can use the "require" function to just suck in that file and define whatever function it is.

    Thanks again for the help!

    Justin

Re: Re: dynamic sub routine definitions?
by dragonchild (Archbishop) on Jul 17, 2002 at 16:04 UTC
    BZZZZZZZT! Please try again.

    You can't use stuff like this to replace an existing function definition, only to add a new one.

    You can too! You just have to be even neato-er.

    FILE1 ----- *{"::SomeFunc"} = sub { print "I'm neater than that!\n" } FILE2.pl -------- sub SomeFunc { print "I'm really neat\n"; } my $neato = 'FILE1'; do $neato; &SomeFunc;

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

      Please read what I wrote more carefully. The paragraph goes on to say:

      What you want can be done, but requires more work: you need a level of indirection.
      You just demonstrated my point: it can be done, but you had to go through the package hash (a level of indirection) to do it.