in reply to Re: How to access outside variable
in thread How to access outside variable

Sorry,

The variable declared as my.

Rewriting the code

my $a=10; { my $a=11; print $a; }

Please consider the file is not an module. It is just simple .pl file.

I want print value of $a is 10 inside the block which is declared on outside.

Replies are listed 'Best First'.
Re^3: How to access outside variable
by ELISHEVA (Prior) on Jan 21, 2011 at 06:02 UTC

    You still can't access the outer value without putting the variables in separate packages and declaring the outer one with our. The second inner my declaration "hides" the first outer my declaration. If you want to access two variables with the same name, you have to give them separate packages, even if it all happens in a single .pl file.

    Packages aren't necessarily modules. You can have many package declarations in a single file and many files sharing the same package declaration. Packages are just namespaces you can use to group together variables and scope them logically rather than via text position (inside/outside curly braces).

    If you really, really don't want to use packages to scope your variables, then you will have to give your inner and outer variables different names. Is there a particular reason you aren't doing that already?

      Thanks for giving good explanation.

      This question asked in my interview panel.

Re^3: How to access outside variable
by Anonyrnous Monk (Hermit) on Jan 21, 2011 at 11:00 UTC

    In case the inner scope isn't just a plain block, but a subroutine, you can use PadWalker to get at the outer scope(s):

    use PadWalker qw(peek_my); my $a=10; sub { my $a=11; my $my = peek_my(1); # one level up print ${$my->{'$a'}}; # 10 print $a; # 11 }->();

    This isn't meant for everyday consumption, though... — better use unambiguous variable names.

Re^3: How to access outside variable
by Anonymous Monk on Jan 21, 2011 at 06:47 UTC
    Do it before you override it