Here's a complete chunk of code that illustrates the problematic behavior (I'll leave it exposed as an added hint):
The observed behavior was an 'undefined subroutine' error -- and yet, if you cut & paste the above code, it will run fine. (So the above is buggy, but simply running it will not reveal the error.)my @cb = (\&callback); $_->() foreach (@cb); sub callback { open(my $fh, "/tmp/somefile") or die; while(<$fh>) { print "orange!\n" if /red/; } }
Spoilers ahead...
It was extra annoying because the error doesn't pop up until the next use of the callback, at which time you just see a strangely mangled @cb array. When I tracked it back, I was rather surprised when my debugging printouts showed that the callback was set to each line of the file I was reading, in turn...
I knew about the scope of $_, and I certainly know about the aliasing of subroutine parameters, but somehow it nevers seemed to be a problem in practice. I could just happily ignore it. Until now.
I believe the root cause is that $_ came well before perl used lexical scopes, and changing it to be lexical would have broken far too many scripts. Maybe we should start working on a new major version of Perl that jettisons some of these legacy features... oh, wait...
In reply to Re: Re: Action at a great distance
by sfink
in thread Action at a great distance
by sfink
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |