in reply to Re^4: Defining global variable in a subroutine
in thread Defining global variable in a subroutine
After having read the linked thread, I'm still not sure what your message is with respect to forking.
For all practical matters, there's no real differnce between accessing an "our" vs. a "my" variable from within a child process. In both cases, the child has access to the variable's value as it was at the time of the fork, but as soon as either the child or the parent modifies it, they become different entities stored at different memory locations (due to the copy-on-write mechanism). In other words, neither the child nor the parent can "update" the variable in the other process.
#!/usr/bin/perl -wl use strict; our $var = "foo"; # my $var = "foo"; # same thing wrt fork sub modify_var { $var = shift; } unless (fork) { sleep 1; print "child: $var"; modify_var("bar"); print "child: $var"; } else { modify_var("baz"); wait; print "parent: $var"; }
prints (as expected):
child: foo child: bar parent: baz
As I'm reading your comment, you'd expect the output to be (?)
child: baz child: bar parent: bar
As you can see, the variable is not shared.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^6: Defining global variable in a subroutine
by flexvault (Monsignor) on Feb 23, 2012 at 10:14 UTC | |
by choroba (Cardinal) on Feb 23, 2012 at 10:23 UTC | |
by flexvault (Monsignor) on Feb 23, 2012 at 10:30 UTC | |
by choroba (Cardinal) on Feb 23, 2012 at 10:38 UTC | |
by flexvault (Monsignor) on Feb 23, 2012 at 11:17 UTC | |
| |
by zwon (Abbot) on Feb 23, 2012 at 11:35 UTC |