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

Hi,

I'm seeking for efficient way to read some constant Perl code from external text file and then execute it in main loop (I guess doing just "do filename" will read file again and again and this is not efficient to do in a loop).

Any advice, example how to do this efficiently ?

Thanks in advance, regards, Bulek.

  • Comment on How to read code from file and execute it in loop ?

Replies are listed 'Best First'.
Re: How to read code from file and execute it in loop ?
by BrowserUk (Patriarch) on Jan 05, 2010 at 20:22 UTC
    1. Wrap the code in the file in sub somename { ... }
    2. then do 'file'; once outside the loop
    3. and call somename() within the loop.

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: How to read code from file and execute it in loop ?
by ikegami (Patriarch) on Jan 05, 2010 at 21:03 UTC
    Place the code to execute repeatedly into a sub. Call the sub in the loop. At this point, you're two lines away from having a module. Why don't you make it a module?
      Hi,

      thanks for response. It seems interesting, can you please help with some simple example ?

      Thanks in advance, regards, bulek.

        # MyModule.pm package MyModule; sub mysub { print("Hello World\n"); } 1;
        use MyModule; MyModule::mysub() for 1..10;
Re: How to read code from file and execute it in loop ?
by jffry (Hermit) on Jan 05, 2010 at 20:39 UTC

    For some extended reading on this topic of using data (the external text file) as executable code, see Dominus' Higher-Order Perl, specifically, Chapter 2: Dispatch Tables.