develooper Front page | perl.beginners | Postings from November 2022

Re: change one line in a large fine

Thread Previous | Thread Next
From:
Kang-min Liu
Date:
November 20, 2022 15:50
Subject:
Re: change one line in a large fine
Message ID:
868rk562wy.fsf@gugod.org

support@openmbox.net 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

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About