in reply to Defining global variable in a subroutine

You can not change the outer scope from within a sub. If you want to have a global variable, declare it in the topmost scope. For including a file, see do.
  • Comment on Re: Defining global variable in a subroutine

Replies are listed 'Best First'.
Re^2: Defining global variable in a subroutine
by flexvault (Monsignor) on Feb 22, 2012 at 14:25 UTC

    choroba,

      "You can not change the outer scope from within a sub. If you want to have a global variable, declare it in the topmost scope."

    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

      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