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

Hi,

I guess it's more mod_perl rather that mason question. I got a situation where I'd like ideally populate hash or array during the server start up and share it between apache processes. Please let me know if the of the book example is what I need:

<Perl> my %foo = (a => 0, b => 1); for (%foo) { push @{ $Location{"/"}->{PerlAddVar} }, [ foo => $_ ]; } </Perl>
thanks

Replies are listed 'Best First'.
Re: mod_perl / mason - variable shared between apache2's children
by perrin (Chancellor) on May 21, 2009 at 04:47 UTC

    All you want to do is fill a hash and then read from it in child processes? Just use a global. Fill it in your httpd.conf in a <Perl> section or in your startup.pl file.

    %My::Conf::Hash = ( foo => 1 );

    You can read that from any apache child process, but you can't modify it after startup. If you want shared read/write data, it becomes a trickier question.

Re: mod_perl / mason - variable shared between apache2's children
by trwww (Priest) on May 21, 2009 at 00:52 UTC

    Hello,

    You can definitely do what you've got there, but it looks to me like it would be more convenient if that data was stored in a config file.

    regards,

      I think that's irrelevant here. What matters is not _how_ you populate those variables, but the fact that you only want to do it once per server instance.

      In ASP and Cold Fusion there's the concept of Application vairables, which are shared between all requests and processes of the server. They were great for configuration options to your application. You'd load them once (from a real config file or a DB most likely; either way relatively slow), and then you could just use the variables in each request without much overhead.

      The most common way to emulate these in perl and PHP seems to be populating the variables on each request, which has always seemed somewhat wasteful to me. (when running under mod_perl I suspect there's probably a way to have real shared variables; I've never used Perl much for web programming myself)

        Right, its not how but when. If you have some read only data (config data), load it before apache forks its children and apache will share the memory without duplicating it in each child.