in reply to Re: Why Is Writing to a Binary File so Hard?
in thread Why Is Writing to a Binary File so Hard?[SOLVED]

Minor tweak to allow reading of a line containing "0" :
while (defined(my $line = <$in>)) { chomp $line; # Zap trailing "\n" efficiently print $out $line,"\r"; }

                "If it happens once, it's a bug. If it happens twice, it's a feature. If it happens more than twice, it's a design philosophy."

Replies are listed 'Best First'.
Re^3: Why Is Writing to a Binary File so Hard?
by afoken (Chancellor) on Feb 01, 2024 at 09:29 UTC

    Minor tweak to allow reading of a line containing "0" :

    while (defined(my $line = <$in>)) { chomp $line; # Zap trailing "\n" efficiently print $out $line,"\r"; }

    Not required:

    #!/usr/bin/perl use strict; use warnings; use autodie; open my $out,'>:raw',"file.tmp"; print $out "a line\na second line\n0"; close $out; open my $in,'<:raw',"file.tmp"; while (my $line=<$in>) { chomp $line; print "read: $line\n"; } close $in;
    >perl foo.pl read: a line read: a second line read: 0 >

    Any line but the last in a file always contains a trailing newline, so $line is guaranteed to be true for all but the last line, and reading empty lines and lines containing only "0" is no problem for all but the last line:

    >perl -E '"0\n" and say "true"' true >perl -E '"\n" and say "true"' true >perl -E '"0" or say "false"' false > perl -E '"" or say "false"' false >perl -E 'undef or say "false"' false >

    The last line WOULD BE a problem if perl would check for truth. But in the special case of readline a.k.a. <HANDLE>, it checks for definedness, not for truth. Quoting perlfunc:

    readline EXPR

    readline

    Reads from the filehandle whose typeglob is contained in EXPR (or from *ARGV if EXPR is not provided). In scalar context, each call reads and returns the next line until end-of-file is reached, whereupon the subsequent call returns undef. [...]

    This is the internal function implementing the <EXPR> operator, but you can use it directly.

    [...]If either a readline expression or an explicit assignment of a readline expression to a scalar is used as a while/for condition, then the condition actually tests for definedness of the expression's value, not for its regular truth value.

    (Emphasis mine)

    Alexander

    --
    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)