in reply to Re: Defining global variable in a subroutine
in thread Defining global variable in a subroutine

choroba,

I believe you are referring to "use strict;", but if you run the following code with "# use strict;", you'll see that you can do what the OP wanted.

my $in = result( 3 ); print "my \$in: $in \t \$out: \$out\n"; sub result { our $out = shift; return( 2 ** $out ); }

This also will work in a forked environment, since the global 'our' variable is in the address space of the parent.

However, I would use "use strict;" and predefine the global variables as you stated.

Thank you

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

Replies are listed 'Best First'.
Re^3: Defining global variable in a subroutine
by Eliya (Vicar) on Feb 22, 2012 at 14:42 UTC
    This also will work in a forked environment, since the global 'our' variable is in the address space of the parent.

    Could you elaborate what you mean by that?

    Almost sounds like you are saying the child process could modify the variable in the parent process.  If so, I'd like to see a demo.

      Eliya,

      If you take a look at Re: Accessing hash from within module, which I commented on how to use/update globals in the parent, I think it gives enough information to explain what I'm talking about.

      Also remember, it you use 'our' in the child, it creates the global in the parent space, and not in the child's address space. That's why you need to LOCK/UNLOCK the global that you are using.

      Good Luck!

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

        An 'our' variable (or any normal variable for that matter) is not shared between parent and child after a fork.
        our $x = 1; my $f = fork; die $! unless defined $f; if ($f) { # parent sleep 1; print "parent: x=$x\n"; # prints 1 } else { $x = 2; exit; }

        Dave.

        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.