|Do you know where your variables are?|
The difference between my and localby cLive ;-) (Prior)
|on Jul 05, 2001 at 08:12 UTC||Need Help??|
Well, this confused the hell out of me, so I thought I'd spend some time getting my head around it.
Quick summary: 'my' creates a new variable, 'local' temporarily amends the value of a variable
There is a subtle difference.
In the example below, $::a refers to $a in the 'global' namespace.
ie, 'local' temporarily changes the value of the variable, but only within the scope it exists in.
so how does that differ from 'my'? 'my' creates a variable that does not appear in the symbol table, and does not exist outside of the scope that it appears in. So using similar code:
ie, 'my' has no effect on the global $a, even inside the block.
But in real life, they work virtually the same?
Yes. Sort of. So when should you use them?
If you use Perl 5 and strict (and I know you do :), you probably haven't noticed any difference between using 'my' and 'local', but will hopefully only use 'local' in the second instance above.
EPP also suggests you use 'local' when messing with variables in another module's namespace, but I can't think of a RL situation where that could be justified - why not just scope a local variable? Perhaps someone could enlighten me?
But, if you ever end up amending some old Perl 4 code that uses local, you need to be aware of the issues and not just do a s/\blocal\b/my/gs on the script :) - sometimes people use the 'features' of local in unusual ways...
Hope that's cleared a few things up.