Explain the difference between "my" and "local" variable scope declarations. ?

Both of them are used to declare local variables.
The variables declared with "my" can live only within the block it was defined and cannot get its visibility inherited functions called within that block, but one defined with "local" can live within the block and have its visibility in the functions called within that block.

Showing Answers 1 - 7 of 7 Answers

Jay Mathuria

  • Oct 21st, 2005
 

The variables declared with my() are visible only within the scope of the block which names them. They are not visible outside of this block, not even in routines or blocks that it calls. local() variables, on the other hand, are visible to routines that are called from the block where they are declared. Neither is visible after the end (the final closing curly brace) of the block at all.

Perl supports three scoping declarations that enable to create private variables (using my) , selectively global variable (using our) and temporary copies of selected global variables (using local) ... my declares a variable to be scoped within the current block and when the block ends, the varaible goes out of scope.. "local" is an temporary value to an gobal variable and the value lasts only for the duaration of the block, it's just has an temporary value while it's being used within that block...

1) My
My creates a new variable and gives a lexical scope for that variable.The variable  is not visible outside the block in which it is defined.

2) Local

Local saves the value of a global variable.It never creates a new variable. Here also, the variable  is not accessible outside the block,but it is visible in the subroutine which is called from the original block."My is more preferring than local". But in various places local is useful , where my is illegal

1) Changing the meaning of a special variable like $/
2) Localized file handles
3) Globing

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions