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

Hallo, I have read that my var in Subroutines are hiden (lixical) for any other nested subroutine that is called from main routine and vice versa. Is it right? If so how can it be possible to "feed" any nested sub? Thank you for your help.

20050329 Edit by castaway: Changed title from 'nested Subruotines and my var'

Replies are listed 'Best First'.
Re: nested Subroutines and my var
by Limbic~Region (Chancellor) on Mar 28, 2005 at 19:51 UTC
    KaiAllard,
    I have read that my var in Subroutines are hiden (lixical) for any other nested subroutine that is called from main routine and vice versa. Is it right?

    Not exactly. It would probably help to read Coping With Scoping. A lexical variable (declared with my) can be seen outwards to the nearest enclosing scope. When you invoke a sub and want to have some variables visible to that sub, you need to pass them to the sub as arguments. The alternative is to declare your lexicals at the same scope as the subs themselves. This is unlikely the right solution.

    Cheers - L~R

Re: nested Subroutines and my var
by ambs (Pilgrim) on Mar 28, 2005 at 19:47 UTC
    Update: Changed accordingly with Roy Johnson reply. I hope I understood correctly what he means. What you say about my vars is correct. If you want a variable to be accessible for other functions calls, use:
    our $bar; sub foo { local $bar = 4; # different $bar zbr(); } sub zbr { print $bar; }
    This code prints 4.

    The correct way is to pass parameters to functions.

    Alberto Simões

      Note that our does not create variables, it merely tells Perl that you're going to be using the global variables you list. You should put the our outside of foo, and use local inside it. Then you're strict safe.

      Caution: Contents may have been coded under pressure.