DEV Community

Discussion on: Yet Another Perl Switch Statement

Collapse
 
grinnz profile image
Dan Book • Edited

The issue is not that it's lexical, but that assigning to a lexical $_ instead of the superglobal $_ broke assumptions that people make that $_ can be used in other code scopes dynamically, such as subroutines you call. If it had started out being lexically aliased by foreach and map it would lead to safer code overall.

local assignment does avoid some danger of action at a distance from aliasing with foreach; in the following code, if some_sub were to assign anything to $_ it would clobber $var as well.

my $var = 'foo';
foreach ($var) {
   some_sub and last;
}
Enter fullscreen mode Exit fullscreen mode

In the end I always recommend using a few more keystrokes and avoiding $_ for this entirely.

Thread Thread
 
matthewpersico profile image
Matthew O. Persico

I whipped up two quick tests:
gist.github.com/matthewpersico/aa1... and gist.github.com/matthewpersico/aa1... and yes, not having that local can be disastrous. So, since for and map and the like are coded "properly", i.e., they localize $_, you should be safe to use them and use functions that call them. But if someone has done this $_ assignment trick and forgets the local, there be dragons.