Yes, exactly what I was thinking of, and what I ran into.

Here's a complete chunk of code that illustrates the problematic behavior (I'll leave it exposed as an added hint):

my @cb = (\&callback); $_->() foreach (@cb); sub callback { open(my $fh, "/tmp/somefile") or die; while(<$fh>) { print "orange!\n" if /red/; } }
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.)

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.