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

Monks, I am attempting to allow a child to update a hash value that the parent can later reference. This appears possible using forks::shared. Here is a trivial example of a parent and child sharing an integer variable.

use forks; use forks::shared; my $GLOBALPRICE : shared; share ($GLOBALPRICE); my $pid = fork (); if (!$pid) { # child $GLOBALPRICE = 100; exit 0; } elsif ($pid) { # daddy sleep (2); print "Global Oils Price is now: " . $GLOBALPRICE . " dollars\n"; }

However, if I turn the shared variable into a hash reference, the parent will not see the child's change. For example:

use forks; use forks::shared; my %GLOBALHASH : shared; share (%GLOBALHASH); my $pid = fork (); if (!$pid) { # child $GLOBALHASH->{OILPRICE} = 100; exit 0; } elsif ($pid) { # daddy sleep (2); print "Global Oils Price is now: " . $GLOBALHASH->{OILPRICE} . " d +ollars\n"; }
In this second case, the parent cannot see the OILPRICE key. Could someone explain how to modify the hash example so that the parent and child can properly share a hash?

Replies are listed 'Best First'.
Re: forked::shared with hashes?
by choroba (Cardinal) on Apr 01, 2011 at 19:26 UTC
    Use strict! Do not mistake $GLOBALHASH for %GLOBALHASH.

      It turns out the problem has to do with the restriction that you should share scalar variables, not complex structures like hashes. So the parent can see the child's hash modifications if you do something like this:

      use forks; use forks::shared; my %GLOBALHASH : shared; my %hashref : shared; $hashref = \%GLOBALHASH; $child = fork (); if (!$child) { # child $hashref->{OILPRICE} = 100; exit 0; } elsif ($child) { # daddy sleep (2); print "Global Oils Price is now: " . $hashref->{OILPRICE} . " doll +ars\n"; }

      However, I've not been able to get this to work with hashes of hashes.

        No, for me, it worked with a hash as well. The restriction applies to threads::shared, not forks::shared.