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

Hi,
local $a=5; &fun1(); sub func{ print $a; local $a=10; print $a; } print $a; output: 5 10 5 Excepted output: 5 10 10

Please how to get excepted output

Replies are listed 'Best First'.
Re: how to acces local varialbe
by jethro (Monsignor) on Feb 09, 2011 at 13:46 UTC

    Why do you use local when you don't want the effect of local?

    local $a=5; &func(); sub func{ print $a; $a=10; print $a; } print $a; Output: 5 10 10

    Also you have a typo with "func" or "fun1", and the output would really be on one line because "\n" is missing from the prints

Re: how to acces local varialbe
by Corion (Patriarch) on Feb 09, 2011 at 13:42 UTC

    Don't use local if you don't understand what it does. Leaving out local makes your code work as you expect. In most cases, it is better to pass values as paramters to a function instead of using and modifying global variables.

    Also, it helps you to get better responses if you actually test your code before you post it. You tried to call a subroutine named fun1 but only declared a subroutine func.

      Sometime it is an actual typo, sometimes its part of the test (can you recognize a runtime error). Sometimes its part of class fun, and sometimes its cruel interviewer trick.
Re: how to acces local varialbe
by Anonymous Monk on Feb 09, 2011 at 13:42 UTC
    Ask your teacher. Oh wait, you're taking a test.
Re: how to acces local varialbe
by renshui (Novice) on Feb 10, 2011 at 07:36 UTC
    Local variables are really global variables in disguise, and they are used to temporarily change the value. The temporary value are confined to be effective inside the innermost enclosing block. In your code, the temporary value 10 of $a is only seen from its declaration to the end of the subroutine.