http://qs1969.pair.com?node_id=94007

Well, this confused the hell out of me, so I thought I'd spend some time getting my head around it.

Probably best to show by example (apologies to Joseph Hall and merlyn for borrowing heavily here from Effective Perl Programming)

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.

$a = 3.14159; { local $a = 3; print "In block, \$a = $a\n"; print "In block, \$::a = $::a\n"; } print "Outside block, \$a = $a\n"; print "Outside block, \$::a = $::a\n"; # This outputs In block, $a = 3 In block, $::a = 3 Outside block, $a = 3.14159 Outside block, $::a = 3.14159

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:

$a = 3.14159; { my $a = 3; print "In block, \$a = $a\n"; print "In block, \$::a = $::a\n"; } print "Outside block, \$a = $a\n"; print "Outside block, \$::a = $::a\n"; # This outputs In block, $a = 3 In block, $::a = 3.14159 Outside block, $a = 3.14159 Outside block, $::a = 3.14159

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.

cLive ;-)