Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

while(<>) doesn't become while(defined($_=<>)) if CORE::GLOBAL::readline is overridden #11150

Open
p5pRT opened this issue Feb 22, 2011 · 3 comments

Comments

@p5pRT
Copy link

p5pRT commented Feb 22, 2011

Migrated from rt.perl.org#84690 (status was 'open')

Searchable as RT84690$

@p5pRT
Copy link
Author

p5pRT commented Feb 22, 2011

From andrew@cleverdomain.org

Ordinarily, Perl changes a construct like while(<>) or
while(readline($handle)) into while(defined($_ = ...)). But if
&CORE​::GLOBAL​::readline is defined when compiling these constructs, $_ won't
be assigned and the defined check won't be added.

This is because when CORE​::GLOBAL​::readline is overriden, S_scan_inputsymbol
in toke.c will generate an OP_ENTERSUB instead of an OP_READLINE, and so
Perl_newLOOPOP will not recognize it as something to transform.

This is fairly low-impact since it only affects people who use
CORE​::GLOBAL​::readline, but it definitely stands in contradiction to the docs.

(This affects every perl since at least 2002 up to blead).

@p5pRT
Copy link
Author

p5pRT commented Feb 23, 2011

From mobrule@gmail.com

Perl's behavior that treats the expressions

  while (<HANDLE>)
  while (readline(<HANDLE>))

as equivalent to

  while (defined($_=readline(HANDLE)))

breaks when &CORE​::GLOBAL​::readline is defined. This makes it
difficult to override the builtin readline function with any legacy
code.

Demo​:

BEGIN {
   *CORE​::GLOBAL​::readline = sub { readline(shift || *ARGV) }
};
($_,$bar) = ("foo\n", "bar\n");
open X, '<', \$bar;
while (<X>) {
   if ($_ eq "bar\n") {
  print "PASS​: <X> is the same as ($_=<X>).\n";
   } elsif ($_ eq "foo\n") {
  print "FAIL​: <X> is not the same as ($_=<X>).\n";
   }
}

This script fails as written but passes if you comment out the BEGIN block.

Another demo​:

Compare​:

    $ perl -MO=Deparse -e 'print while <>'
    print $_ while (defined($_ = <ARGV>));   <---- $_ is set implicitly
    -e syntax OK

with​:

    $ perl -MO=Deparse -e 'BEGIN{*CORE​::GLOBAL​::readline=sub{}}' \
             -e 'print while <>'
    sub BEGIN {
        *CORE​::GLOBAL​::readline = sub {
        }
        ;
    }
    print $_ while readline(ARGV);          <----- $_ is not set !
    -e syntax OK

See also​: http​://stackoverflow.com/questions/5081767/.

If this isn't a bug, then it is at least underdocumented.

@p5pRT
Copy link
Author

p5pRT commented Dec 17, 2011

@jkeenan - Status changed from 'new' to 'open'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants