Re: change one line in a large fine

[email protected] (Kang-min Liu)
Newsgroups perl.beginners
Message-ID <[email protected]>
[email protected] writes:
> May i ask a question about reading file?
>
> while(0){ print 'hi' }
>
> Will never print hi.
>
> cat 1.txt:
> 0
>
> open FH, '1.txt' or die;
> while(<FH>) { print 'hi' }
>
> This will print hi.
>
> Since $_ == 0 here, why while become true?

This seems to be more about what are true-y and what are false-y.

If the content of 1.txt is one line containing a character "0" follewed
by the newline character, that means doing <FH> would make $_
contain "0\n", that's two characters, not one.

"0\n" would be a true-y value while it is still numerically the same as
0 when testing with the operator `==`. The `==` operator always convert
both of its operants to numerical values before doing the
comparison. Similarly `eq` operator always converts both operants to
string before doing the comparison.

There are a lot of ways to make variables being numerically 0 while also
being a true-y value. Most of them are strings with leading zeros. You
could try editing the following program to play around:

    use strict;

    $_ = "0\n";

    print "true-y\n" if $_;

    print "== 0\n" if $_ == 0;
    print "eq 0\n" if $_ eq 0;

    print "eq \"0\"\n" if $_ eq "0";
    print "== \"0\"\n" if $_ == "0";

There are also a lot of values with leading "0" which would be true-y,
but fail all 4 other if-s. :-)

BTW, really, don't actually write `eq 0` or `== "0"`, they just look weird.

--
Cheers,
Kang-min Liu
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.