in reply to Doubt on defined-ness

So why is the first idiom "suboptimal"?

I haven't looked up that passage in the Camel Book, so I'm not sure what it's referring to... but maybe it's trying to point out that 'if ($_=<FH>) ...' could evaluate to false in circumstances where you don't want it to be false (the line being empty or zero). Just a guess though.

(Update: crossed out "empty", because - upon rethinking - I can't really come up with any case where $_ would be the emtpy string — not even when fiddling with the input record separator...)

Update 2: ikegami actually did find a variant where <> can return an empty string...  So, I might in theory un-strike that part again. But I won't — I guess it's unlikely anyone will run into this case by accident :)

Replies are listed 'Best First'.
Re^2: Doubt on defined-ness
by ikegami (Patriarch) on Jun 18, 2008 at 23:48 UTC

    This isn't quite you had in mind, but not only did I find a case where <> returns an empty string, it does so before the last "line".

    >perl -MData::Dumper -e"while (<{,0,a}>) { print Dumper $_ }" $VAR1 = ''; $VAR1 = '0'; $VAR1 = 'a';

    A tied handle could do it too, say one that autochomps.

Re^2: Doubt on defined-ness
by ikegami (Patriarch) on Jun 18, 2008 at 22:48 UTC
    Maybe on a non-blocking handle?

      Interesting idea... but I can't even get that to return an empty string:

      #!/usr/bin/perl use Fcntl; fcntl(STDIN, F_GETFL, my $flags) or die "Couldn't get flags: $!\n"; fcntl(STDIN, F_SETFL, $flags|O_NONBLOCK) or die "Couldn't set flags: $ +!\n"; $_=<STDIN>; use Data::Dumper; print Dumper $_; # --> prints $VAR1 = undef;

      Maybe you can construct a better case (?)

        I said "maybe", as in "it's something to try". I have no experience with non-blocking handles. Reportedly, IO::Handle::blocking doesn't even work on my OS.

        That said, I do have access to a linux machine, and I'm getting the same result (undef) using STDIN->blocking(0).

Re^2: Doubt on defined-ness
by bart (Canon) on Jun 19, 2008 at 12:19 UTC
    I remember I brought up that bug, back in the days that defined was not yet implied...

    If your text file ended with a "0" on a line of its own, without appended newline, that last line was ignored.

    Worse: if that happened in a file in the middle of a list of files in @ARGV, then while(<>) was interrupted at the end of that file, and the rest of the files that came after it were simply ignored.

    As for the Camel Book: historically, originally defined was not implied. The text in the book probably just still reflects that.