Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Accessing hash from within module

by flexvault (Monsignor)
on Feb 12, 2012 at 09:40 UTC ( [id://953299]=note: print w/replies, xml ) Need Help??


in reply to Accessing hash from within module

hmonroe,

I have a 20,000+ line package with about 6 modules, and I use 'our' in parent that forks copies of itself once all global data has been initialized. I'm sure this is just another way of looking at the problem, but it does work for forked copies, so I'm sure it will work for all modules sharing one address space. The sample code is just a skeleton.

parent code:

{ ## Parent our ( %hash, @array, $scalar, $LOCK ); ## Global data my $lockfile = "./GobalLock"; open ( $LOCK, ">>", $lockfile ) or die "Can't open $lockfile; $!\n"; ... # code to fork and maintain number of children }

If your package is running as a single user, you don't have to lock the parent globals, but you must lock them if more than one module needs access to the global data. When the children want to get or update global data:

{ my $need; ... if ( flock( $LOCK, LOCK_SH ) ) ## Get a copy of Global data { $need = $hash{"stuff"}; flock( $LOCK, LOCK_UN ); } else { die "$!\n"; } ... if ( flock( $LOCK, LOCK_EX ) ) ## Update the Global data { $hash{"stuff"} = $need; flock( $LOCK, LOCK_UN ); } else { die "$!\n"; } ... }

If you scope each module with a separate pair of brackets {}, and you are of course running with 'strict' and 'warnings', sometimes I get an error that I need to define a global. I just add the 'our ...' after the top '{' and it covers the entire module. It doesn't seem to happen as much as in the past, but if you see it just add the our in scope.

Good Luck!

"Well done is better than well said." - Benjamin Franklin

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://953299]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2024-04-20 03:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found