I'm not sure that I understand your question, since in your example the use of globals should be very easy, but if you want to multi-fork(thread?) your package, then possible this will help.
In Unix/Linux, I use this technique:
#!/usr/local/bin/perl -w
# Server.plx
use warnings;
use strict;
our $root = "/usr/local"; # This should be a very protected location
+! Different filesystem is even better
our ( $GlobalLock, %HashA, @ArrayA . . . );
## eval
{ require "functions.pl";
my $ret = Setup(0); ## Setup subroutine initializes the global va
+riables only once
## I usually put the 'require's in the Setup
+subroutine
## Then I can test with: perl -e 'require Ser
+ver.plx; my $r = Setup(4);'
## Errors are now run-time errors the (4) is
+debug level for logging.
}
if ( $@ )
{ ## didn't work, you could retry or whatever
}
# fork childern
while ( 1 )
{ # check on children
}
And now the child activity after the fork.
#!/usr/local/bin/perl -w
# Server.plx ( really child after fork! )
use warnings;
use strict;
our $root;
{
## $GlobalLock was opened by parent and is available to children for
+processing
## Child is waiting for work ( in my case usually a socket wait )
## If child needs to work on any global variables, should lock/unlock
+ with fork.
## And always check the return code from flock!
}
Obviously, a lot of code is needed to complete this sample, but the general idea is there. One thing that is critical, is to lock the globals when the children use them. For this, I use the $GlobalLock file and use flock to lock/unlock when ever I access a global variable.
The global variables will remain in the parent address space, and may be used by the children. One strange thing that I have observed, is that after you check the syntax of your package ( perl -c -w server.plx ), sometimes I get run-time errors that many global can't be accessed from a subroutine. When I add 'our $root;' to the subroutine, all the run-time errors go away. You may have experienced this, and hence you question!
This may be over-kill for your needs, but you're next step may be to add threads and work in parallel. Some one else on this list will have to coach you on what locking/unlocking requirements are needed for threads. A lot of programmers learn the hard way, myself included! You need to Lock it!
Thank you and Good Luck
"Well done is better than well said." - Benjamin Franklin
|