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

Re: change one line in a large fine

Thread Previous | Thread Next
From:
support
Date:
November 20, 2022 23:45
Subject:
Re: change one line in a large fine
Message ID:
29c7edc3c510671bd5c403adf41cb52e99ee76f6@openmbox.net
please see this ops:

$ echo -n 0 > 1.txt

1.txt has only one line without eof.

but the script below still got true for matching 0.

$ cat test.pl 
use strict;

open HD,"1.txt" or die $!;
while(<HD>){
  print "hi";
}


which will print hi.

can you help further?


November 20, 2022 at 11:19 PM, "Kang-min Liu" <gugod@gugod.org> wrote:


> 
> 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
> 
> -- 
> To unsubscribe, e-mail: beginners-unsubscribe@perl.org
> For additional commands, e-mail: beginners-help@perl.org
> http://learn.perl.org/
>

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